Search code examples
regexsearchintellij-ideaidephpstorm

Reference to captured group value with \g<...>


I have a pattern like this

absint\(\s?(\$[A-Za-z0-9_]+)\s?\)\s?={2,3}\s?\g<1>|(\$[A-Za-z0-9_]+)\s?==\s?absint\(\s?\g<2>\s?\)

which findes code like $id == absint($id) or $id == absint($id). It works fine with preg_match function, in https://regex101.com but PHPStorm doesn't support this syntax. How can I do exactly the same thing in PHPStorm search ?


Solution

  • It appears you cannot use recursion in PHP Storm. You may repeat the pattern though:

    absint\(\s?\$\w+\s?\)\s?={2,3}\s?\$\w+|\$\w+\s?={2,3}\s?absint\(\s?\$\w+\s?\)
               ^^^^^                 ^^^^^ ^^^^^                       ^^^^^
    

    See the regex demo (JS flavor chosen that does not support pattern recursion).

    The \w matches letters, digits or underscores, and in case of a non-Unicode-aware regex, is equal to [A-Za-z0-9_].

    Now, if you mean to only match the same variables on both ends, you may use backreferences (instead of the recursion constructs):

    absint\(\s?(\$\w+)\s?\)\s?={2,3}\s?\1|(\$\w+)\s?={2,3}\s?abs‌​int\(\s?\2\s?\)
               xxxxxxx                 xx yyyyyyy                       yy
    

    Backreferences do not repeat (reuse) the group patterns (as is the case with \g<1> or (?1)), but they are placeholders for the text captured with the corresponding groups.

    See Using Backreferences To Match The Same Text Again vs. Regular Expression Subroutines.