简体   繁体   中英

Python inconsistencies reading regex file

I have a regex file that I am reading in and compiling. The issue I am having is the regex will sometimes leading \\ .

Z\\d*\\.file_\\.?

instead of

Z\d*\.file_\.?

It sometimes matching but others not.

Most likely it does not match when you use raw string and double backslash.

s = "ABC 23"

re.findall('\d+',s)
['23']

re.findall(r'\d+',s)

['23']

re.findall('\\d+',s)
['23']

re.findall(r'\\d+',s)     

[]

I don't know if that is what you want but if you read documentation of regular expression operations

It says :

"Regular expressions use the backslash character ('\\') to indicate special forms or to allow special characters to be used without invoking their special meaning"

And also :

"The solution is to use Python's raw string notation for regular expression patterns; backslashes are not handled in any special way in a string literal prefixed with 'r'"

Example:

regex= re.compile(r'string')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM