Matching two lines in Python that have an escape character (E :()

Example:

temp=PID ie() Invoked u 5 1n 5n T ss each=PID ie() Invoked u 5 1n 5n T ss 

I tried this: re.match(temp, each) but it doesn't match

+2
source share
2 answers

First, the first argument in re.match() is a regular expression, and python will treat them as regular notation, and the sine in temp brackets, which will be evaluated as capture groups.

You need to escape from them if you want to have the correct match:

 >>> temp = "PID ie\(\) Invoked u 5 1n 5n T ss" >>> re.match(temp, each) <_sre.SRE_Match object; span=(0, 46), match='PID ie() Invoked u 5 1n 5n T ss'> 

Or you can use re.escape() to avoid regex notations:

 >>> re.match(re.escape(temp), each) <_sre.SRE_Match object; span=(0, 46), match='PID ie() Invoked u 5 1n 5n T ss'> >>> 

Secondly , if you just want to check for equality, you can simply use the == operator.

 temp == each 
+2
source

If you need to check if one line starts with another (this is what re.match does, since it only matches at the beginning of the line), use each.startswith(temp) . Or use re.match(re.escape(temp), each) , since re.escape will automatically exit (add \ ) in front of all the "special" characters.

If you need to check whether one begins with the other, you do not need a regular expression:

 each.startswith(temp) 

or with regex:

 m = re.match(re.escape(temp), each) 

If you need to check if it is equal to another, you need to add an end of line binding:

 m = re.match("{0}$".format(re.escape(temp)), each) 

If you need to check if one of them contains, you need to use re.search :

 m = re.search(re.escape(temp), each) 

or not a regular expression:

 each.find(temp) > -1 

Watch the IDEONE demo :

 import re temp="PID ie() Invoked u 5 1n 5n T ss" each="PID ie() Invoked u 5 1n 5n T ss" # Check if one starts with another print(each.startswith(temp)) # Same with regex: print(re.match(re.escape(temp), each)) # Check if one *equals* another print(re.match("{0}$".format(re.escape(temp)), each)) # Check if one *contains* another print(each.find(temp) > -1) print(re.search(re.escape(temp), each)) 
0
source

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


All Articles