python - How does re.match and re.search with '^' differ? -


it seems re.match , re.search w/ '^' same thing, except re.search can use re.multiline flag making more flexible.

string ="""u.s. stock-index futures pointed solidly higher open on monday north korea. issue overshadowed state of  equity market, earnings  have been strong @ time of high  employment , low inflation,  valuations ppear elevated many metrics, north korea"""  import re   re.search('^north korea\.?', string)  # no match re.match('^north korea\.?', string) # no match re.search('^north korea\.?', string, flags = re.multiline ).group() #match 

are there benefits of using 1 on other?

re.match() checks match @ beginning

>>> re.match("c", "abcdef")    # no match >>> re.search("c", "abcdef")   # match <_sre.sre_match object @ ...> 

re.search() checks match anywhere in string. if want find substring, use re.search()

>>> re.match("c", "abcdef")    # no match >>> re.search("^c", "abcdef")  # no match >>> re.search("^a", "abcdef")  # match <_sre.sre_match object @ ...> 

both case, search , match same thing because ^

^ (caret.) matches start of string. thus, force re.search search beginning of string (without multiline).

with ^ , multiline, re.search() , re.match() different because:

re.match() find beginning of string. so, if first line not match, not match.

re.search() match anywhere on string, thus, can match second, third, ... new line.

in document, said

note in multiline mode match() matches @ beginning of string, whereas using search() regular expression beginning '^' match @ beginning of each line.


Comments

Popular posts from this blog

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

python Tkinter Capturing keyboard events save as one single string -

sql server - Why does Linq-to-SQL add unnecessary COUNT()? -