Search code examples
pythonregexquotation-marks

Regex in Python: Allow double and single quotation marks


With a Python script I want to extract parameters from my Dart code (Strings).

When I have AppLocalizations.of(context).translate("translationKey"), I want to get translationKey.

The following code is working perfectly for double quotation marks ("..."), but I can't get it to work for single quotation marks ('...').

for line in dartFile:
    quotes = re.findall('AppLocalizations.of\(context\).translate\("([^"]*)"\)', line)

How can I also get AppLocalizations.of(context).translate('translationKey') working?


Solution

  • This should work for you

    for line in dartFile:
        quotes = re.findall("""AppLocalizations\.of\(context\)\.translate\([\"']([^\"']*)[\"']\)""", line)
    

    You can use """ to write strings more freely, you can even go to the next line without using \n.