Search code examples
pythonregexlookbehind

Python regex to find only second quotes of paired quotes


I wondering if there is some way to find only second quotes from each pair in string, that has paired quotes.

So if I have string like '"aaaaa"' or just '""' I want to find only the last '"' from it. If I have '"aaaa""aaaaa"aaaa""' I want only the second, fourth and sixth '"'s. But if I have something like this '"aaaaaaaa' or like this 'aaa"aaa' I don't want to find anything, since there are no paired quotes. If i have '"aaa"aaa"' I want to find only second '"', since the third '"' has no pair.

I've tried to implement lookbehind, but it doesn't work with quantifiers, so my bad attempt was '(?<=\"a*)\"'.


Solution

  • import re
    reg = re.compile(r'(?:\").*?(\")')
    

    then

    for match in reg.findall('"this is", "my test"'):
        print(match)
    

    gives

    "
    "