如何匹配python中$(…)中的字符串
发布时间:2020-12-20 12:08:47 所属栏目:Python 来源:网络整理
导读: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(")") prin
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)这样的字符串.但现在这甚至匹配(你好). 我真的很陌生.那我在这里做错了什么? 解决方法
使用以下正则表达式:
$(([^)]+)) 它匹配$,然后是(,然后是直到最后的任何东西),并捕获括号之间的字符. 这里我们确实逃避了$,(和),因为当你使用一个接受正则表达式的函数(比如findall)时,你不希望$被视为特殊字符$,而是作为文字“$”(同样成立)对于(和)).但请注意,由于您要捕获外括号之间的文本,因此内括号未被引用. 请注意,当您不使用正则表达式时,不需要转义特殊字符. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |