gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 04:42:54 31 4
gpt4 key购买 nike

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/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com