regex - How can Python's regular expressions work with patterns that have escaped special characters? -


is there way python's regular expressions work patterns have escaped special characters? far limited understanding can tell, following example should work, pattern fails match.

import re  string = r'this string ^g\.$s'   # string search pattern = r'^g\.$s'                     # pattern use  string = re.escape(string)              # escape special characters pattern = re.escape(pattern)  print(re.search(pattern, string))       # prints "none" 

note:
yes, question has been asked elsewhere (like here). can see, i'm implementing solution described in answers , it's still not working.

why on earth applying re.escape to string?! want find "special" characters in that! if apply pattern, you'll match:

>>> import re >>> string = r'this string ^g\.$s' >>> pattern = r'^g\.$s' >>> re.search(re.escape(pattern), re.escape(string))  # nope >>> re.search(re.escape(pattern), string)  # yep <_sre.sre_match object @ 0x025089f8> 

for bonus points, notice need re.escape pattern 1 more times string:

>>> re.search(re.escape(re.escape(pattern)), re.escape(string)) <_sre.sre_match object @ 0x025d8de8> 

Comments

Popular posts from this blog

javascript - Karma not able to start PhantomJS on Windows - Error: spawn UNKNOWN -

c# - Display ASPX Popup control in RowDeleteing Event (ASPX Gridview) -

Nuget pack csproj using nuspec -