with open('templates/data.xml', 'r') as s:
for line in s:
line = line.rstrip() #removes trailing whitespace and '\n' chars
if "\\$\\(" not in line:
if ")" not in line:
continue
print(line)
start = line.index("$(")
end = line.index(")")
print(line[start+2:end])
我需要匹配类似于 $(hello) 的字符串。但现在这甚至匹配(你好)。
我真的是 python 新手。那么我在这里做错了什么?
最佳答案
使用以下正则表达式:
\$\(([^)]+)\)
它匹配 $
,然后是 (
,然后是最后一个 )
之前的任何内容,并捕获括号之间的字符。
这里我们确实对 $
、(
和 )
进行了转义,因为当您使用接受正则表达式的函数时(例如 findall
),您不希望将 $
视为特殊字符 $
,而是将其视为文字“$”( (
和 )
)也是如此。但是,请注意内括号没有被引用,因为您想要捕获外括号之间的文本。
请注意,当您不使用正则表达式时,您不需要转义特殊字符。
关于python - 如何在python中匹配$(....)中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31941538/