gpt4 book ai didi

python反斜杠正则表达式的乐趣

转载 作者:太空宇宙 更新时间:2023-11-04 09:10:21 24 4
gpt4 key购买 nike

unc = r'\\foo\bar'
string1 = r'\\foo\bar'
string2 = r'\\\\foo\\bar'

if unc == string1:
print "I wish to make a complaint"

if re.match(string1, unc):
print "Ello miss"

if re.match(string2, unc):
print "Sorry I have a cold"

输出是:

I wish to make a complaint
Sorry I have a cold

似乎 re.match 操作重新转义了文字字符串,因此“Ello miss”永远不会发生。

谁能解释为什么我必须在首先将字符串设置为文字时重新转义反斜杠?

我想在配置文件中保留一个 UNC 路径列表,并且我不想在其中转义字符串。当比较器工作时,提供一个可用的正则表达式选项会很有用。

最佳答案

\ 字符是正则表达式中的特殊字符,必须进行转义才能按字面意思理解。因此,如您所见,要匹配字符串 \\foo\bar,您需要正则表达式 \\\\foo\\bar。您可以使用函数 re.escape 为您创建这样一个正则表达式,以包含在更大的表达式中。

>>> re.escape(r'\\foo\bar')
'\\\\\\\\foo\\\\bar' # ouch

关于python反斜杠正则表达式的乐趣,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16019295/

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