Python regex: matching a parenthesis within parenthesis

前端 未结 6 1672
滥情空心
滥情空心 2020-12-14 16:52

I\'ve been trying to match the following string:

string = \"TEMPLATES = ( (\'index.html\', \'home\'), (\'base.html\', \'base\'))\"

But unfo

6条回答
  •  独厮守ぢ
    2020-12-14 17:32

    First of all, using \( isn't enough to match a parenthesis. Python normally reacts to some escape sequences in its strings, which is why it interprets \( as simple (. You would either have to write \\( or use a raw string, e.g. r'\(' or r"\(".

    Second, when you use re.match, you are anchoring the regex search to the start of the string. If you want to look for the pattern anywhere in the string, use re.search.

    Like Joseph said in his answer, it's not exactly clear what you want to find. For example:

    string = "TEMPLATES = ( ('index.html', 'home'), ('base.html', 'base'))"
    print re.findall(r'\([^()]*\)', string)
    

    will print

    ["('index.html', 'home')", "('base.html', 'base')"]
    

    EDIT:

    I stand corrected, @phooji is right: escaping is irrelevant in this specific case. But re.match vs. re.search or re.findall is still important.

提交回复
热议问题