python 正则表达式无法匹配涉及反斜杠的字符串

标签 python python-2.7

C:\Users\dibyajyo>python                                                              
Python 2.7.9 (default, Dec 10 2014, 12:24:55) [MSC v.1500 32 bit (Intel)] on win32    
Type "help", "copyright", "credits" or "license" for more information.                
>>>                                                                                   
>>>                                                                                   
>>> import re                                                                         
>>> outString = 'DiagnosticPath = fs0:\\efi\\tools'                                   
>>> print outString                                                                   
DiagnosticPath = fs0:\efi\tools                                                       
>>> expString = 'DiagnosticPath = fs0:\\efi\\tools'                                   
>>> print expString                                                                   
DiagnosticPath = fs0:\efi\tools                                                       
>>> matchObj = re.search( expString, outString, re.M|re.I)                            
>>> if matchObj:                                                                      
...   print matchObj.group()                                                          
...                                                                                   
>>>

两者expStringoutString字符串是相同的,但不确定为什么我没有找到任何匹配...

最佳答案

引自python's re documentation :

Regular expressions use the backslash character ('\') to indicate special forms or to allow special characters to be used without invoking their special meaning. This collides with Python’s usage of the same character for the same purpose in string literals; for example, to match a literal backslash, one might have to write '\\\\' as the pattern string, because the regular expression must be \\, and each backslash must be expressed as \\ inside a regular Python string literal.

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'. So r"\n" is a two-character string containing '\' and 'n', while "\n" is a one-character string containing a newline. Usually patterns will be expressed in Python code using this raw string notation.

所以如果你使用:

expString = r'DiagnosticPath = fs0:\\efi\\tools'

你的代码应该可以工作。

关于python 正则表达式无法匹配涉及反斜杠的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30172635/

相关文章:

Python - "in"语句搜索对象列表缓慢

python - 有人可以向我解释这个非常基本的 Python 代码吗?

python - 使用 PyPi 时在 Python 3 代码库中支持 Python 2 的好方法是什么?

python - 我如何使用字符串来表示 sqlalchemy 对象属性?

python - 检查两个文件指针是否指向 Python 中的同一个文件

python - 我无法从程序中获取授权码

python - 创建引用表的一部分的别名

python - 值错误 : No Shapely geometry can be created from null value

python - 当我的计算机无法识别或定位 Gym 时,如何正常使用 OpenAI Gym?

python - 对引号进行分组并忽略转义引号