Is there an easy way to switch between using and ignoring metacharacters in Python regular expressions?

Is there a way to switch compilation or use metacharacters when compiling regular expressions? The current code looks like this:


Current code:

import re the_value = '192.168.1.1' the_regex = re.compile(the_value) my_collection = ['192a168b1c1', '192.168.1.1'] my_collection.find_matching(the_regex) result = ['192a168b1c1', '192.168.1.1'] 


An ideal solution would look like :

 import re the_value = '192.168.1.1' the_regex = re.compile(the_value, use_metacharacters=False) my_collection = ['192a168b1c1', '192.168.1.1'] my_collection.find_matching(the_regex) result = ['192.168.1.1'] 

An ideal solution would allow the library to re handle the disconnection of metacharacters to avoid the need to get as much involved in the process as possible.

+6
source share
2 answers

Nope. But:

 the_regex = re.compile(re.escape(the_value)) 
+7
source

Use re.escape() for this.

The returned string with all non-alphabets of the backslash; this is useful if you want to match an arbitrary literal string that can contain regular expression metacharacters in it.

 >>> import re >>> re.escape('192.168.1.1') '192\\.168\\.1\\.1' 
+6
source

Source: https://habr.com/ru/post/958613/


All Articles