Quantcast
Channel: Python extract pattern matches - Stack Overflow
Viewing all articles
Browse latest Browse all 12

Answer by Grzesik for Python extract pattern matches

$
0
0

Below is a simple solution to the problem

import reexcept_substring = "\w+_\w+_\w+"original_string = """someline abcsomeother linename my_user_name is validsome more lines"""m=re.findall(except_substring, original_string)if m:    print(m[0]) #--> "my_user_name"else:    print("Substring was not found")

Or we can make the function:

def replace_all_exept_substring(original_string: str, except_substring: str) -> str:"""     The function gets the substring to be skipped from the whole string     can get it in the form of a single word, e.g. "NoSuchUser"     or a regular expression, e.g. "Message.*has.been.*rejected."     original_string : the whole phrase to search for     except_substring : the phrase/word to be returned     return : the message sent to the following e mail address has been rejected"""     m = re.findall(except_substring, original_string)     # A+1 if A > B else A-1     return m[0] if m else original_string
m=replace_all_exept_substring(original_string, except_substring)print(m) #--> "my_user_name" or "original_string"

Viewing all articles
Browse latest Browse all 12

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>