Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to match string in single or double quoted using regex

Tags:

regex

quotes

I'm trying to write a regex that matches strings as the following:

translate("some text here")

and

translate('some text here')

I've done that:

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

but how to add if there are single quotes, not double. It should match as single, as double quotes.

like image 559
ivva Avatar asked Mar 12 '23 01:03

ivva


1 Answers

You could go for:

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

See a demo for this approach on regex101.com.


In PHP this would be:
<?php

$regex = '~
            translate\( # translate( literally
            ([\'"])     # capture a single/double quote to group 1
            .+?         # match anything except a newline lazily
            \1          # up to the formerly captured quote
            \)          # and a closing parenthesis
         ~x';

if (preg_match($regex, $string)) {
    // do sth. here
}
?>

Note that you do not need to escape both of the quotes in square brackets ([]), I have only done it for the Stackoverflow prettifier.
Bear in mind though, that this is rather error-prone (what about whitespaces, escaped quotes ?).


In the comments the discussion came up that you cannot say anything BUT the first captured group. Well, yes, you can (thanks to Obama here), the technique is called a tempered greedy token which can be achieved via lookarounds. Consider the following code:
translate\(
(['"])
(?:(?!\1).)*
\1
\)

It opens a non-capturing group with a negative lookahead that makes sure not to match the formerly captured group (a quote in this example).
This eradicates matches like translate("a"b"c"d") (see a demo here).


The final expression to match all given examples is:
translate\(
(['"])
(?:
   .*?(?=\1\))
)
\1
\)
like image 53
Jan Avatar answered May 03 '23 13:05

Jan