Skip to content Skip to sidebar Skip to footer

Use Python 3 Regex To Match A String In Double Quotes

I want to match a string contained in a pair of either single or double quotes. I wrote a regex pattern as so: pattern = r'([\'\'])[^\1]*\1' mytext = ''bbb'ccc'ddd' re.match(patter

Solution 1:

In your regex

([\"'])[^\1]*\1

Character class is meant for matching only one character. So your use of [^\1] is incorrect. Think, what would have have happened if there were more than one characters in the first capturing group.

You can use negative lookahead like this

(["'])((?!\1).)*\1

or simply with alternation

(["'])(?:[^"'\\]+|\\.)*\1

or

(?<!\\)(["'])(?:[^"'\\]+|\\.)*\1

if you want to make sure "b\"ccc" does not matches in string bb\"b\"ccc"


Solution 2:

You should use a negative lookahead assertion. And I assume there won't be any escaped quotes in your input string.

>>> pattern = r"([\"'])(?:(?!\1).)*\1"
>>> mytext = '"bbb"ccc"ddd'
>>> re.search(pattern, mytext).group()
'"bbb"'

Solution 3:

You can use:

pattern = r"[\"'][^\"']*[\"']"

https://regex101.com/r/dO0cA8/1


[^\"']* will match everything that isn't " or '


Post a Comment for "Use Python 3 Regex To Match A String In Double Quotes"