如何在python中匹配$(....)中的字符串

din*_*707 3 python regex python-2.7

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])
Run Code Online (Sandbox Code Playgroud)

我需要匹配像$(hello)这样的字符串.但现在这甚至匹配(你好).

我真的很陌生.那我在这里做错了什么?

Mar*_*oun 6

使用以下正则表达式:

\$\(([^)]+)\)
Run Code Online (Sandbox Code Playgroud)

它匹配$,然后匹配,(直到最后一个),并在括号之间捕获字符.

在这里,我们没有逃避$,(而且)因为当你使用接受一个正则表达式(如函数findall),你不希望$被当作特殊字符$,但随着文字 "$"(同样适用于()).但请注意,由于您要捕获外括号之间的文本,因此内括号未被引用.

请注意,当您不使用正则表达式时,不需要转义特殊字符.