为什么我的Python正则表达式findall返回一个意外的匹配列表?
我正在尝试检测以下模式: 偶数的为什么我的Python正则表达式findall返回一个意外的匹配列表?,python,regex,Python,Regex,我正在尝试检测以下模式: 偶数的\,后跟$和文本 这是有效的:\$hello或$bye 我正试图用Python实现这一点: txt = r"\\$hello" regex = r"(?<!\\)(\\\\)*(?!\\)\$[a-zA-Z_]\w*" x = re.findall(regex, txt) if x: print(x) else: print("No match") txt=r“\\$hello” re
\
,后跟$
和文本
这是有效的:\$hello
或$bye
我正试图用Python实现这一点:
txt = r"\\$hello"
regex = r"(?<!\\)(\\\\)*(?!\\)\$[a-zA-Z_]\w*"
x = re.findall(regex, txt)
if x:
print(x)
else:
print("No match")
txt=r“\\$hello”
regex=r“(?我不明白你的regex背后的意思,所以我不能说你到底哪里出了错。但是下面是你对匹配模式的口头描述(“偶数个反斜杠,后跟一个美元符号,后跟一个文本”)并在$
符号后检索文本:
重新导入
txt=r“\\$hello”
regex=r“(\\)*\$(.*)”
match=re.findall(regex,txt)[0][1]
如果要在匹配字符串中包含美元符号,只需调整:
regex=r“(\\)*(\$.*)”
您捕获了错误的内容。将(\\\\\)
设置为非捕获组,如下所示:(?:\\\\)
并捕获斜杠后的部分:(\$[a-zA-Z]\uw*)
。然后您的代码给出x=['$hello']
txt = r"\\$hello"
regex = r"(?<!\\)(?:\\\\)*(?!\\)(\$[a-zA-Z_]\w*)"
x = re.findall(regex, txt)
# x: ['$hello']
txt=r“\\$hello”
regex=r“(?@jonathan.scholbach我很确定,在原始表达式中,\不需要转义。我的文本输入是正确的。它可以这样写:“\\\\\$hello”
或r“\\\$hello”
。两者的意思相同(两个斜杠后跟$hello)。这是一个已知的问题和解决方案,请参阅
txt = r"\\$hello"
regex = r"(?<!\\)(\\\\)*(?!\\)(\$[a-zA-Z_]\w*)"
x = re.findall(regex, txt)
# x: [('\\\\', '$hello')]