quotes - How to match string in single or double quoted using regex -


i'm trying write regex matches strings following:

translate("some text here")

and

translate('some text here')

i've done that:

preg_match ('/translate\("(.*?)"\)*/', $line, $m) 

but how add if there single quotes, not double. should match single, double quotes.

you go for:

translate\( # translate( literally (['"])      # capture single/double quote group 1 .+?         # match except newline lazily \1          # formerly captured quote \)          # , closing parenthesis 

see demo this approach on regex101.com.


in php be:

<?php  $regex = '~             translate\( # translate( literally             ([\'"])     # capture single/double quote group 1             .+?         # match except newline lazily             \1          # formerly captured quote             \)          # , closing parenthesis          ~x';  if (preg_match($regex, $string)) {     // sth. here } ?> 

note not need escape both of quotes in square brackets ([]), have done stackoverflow prettifier.
bear in mind though, rather error-prone (what whitespaces, escaped quotes ?).


in comments discussion came cannot anything first captured group. well, yes, can (thanks obama here), technique called tempered greedy token can achieved via lookarounds. consider following code:

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

it opens non-capturing group negative lookahead makes sure not match formerly captured group (a quote in example).
eradicates matches translate("a"b"c"d") (see a demo here).


final expression match given examples is:

translate\( (['"]) (?:    .*?(?=\1\)) ) \1 \)