Matheus Silva Matheus Silva - 4 months ago 36
PHP Question

Capturing group with optional start and end characters

i have the follow string:

find me String1\String2\String3
, so i wanna capture string1, 2 and 3 if they exist. String 3 can be optional.

So far, what i could make is:
(?<=find me)\s(\\?[\w]+\\?){1,3}
, my assumption was:

  • The string should have
    find me
    at the beggining but it should not be captured

  • a whitespace

  • a group with
    as optional character at the beggining of the string, a word following it and
    at the end of it, optional too, it can appear from 1 to 3 times.

What is wrong with my regex pattern?


Assuming your regex flavor supports \G, you can use this regex to capture all 3 strings separately:

(?<=find me |(?<!^)\G\\)\w+

RegEx Demo

\G asserts position at the end of the previous match or the start of the string for the first match.

\G matches a position that either line start OR end of the previous match. In this case I also have a negative lookbehind (?<!^) which means don't match line start, hence it makes \G match only the positions that end of the previous matches. For your example, it matches twice i.e. end of String1 and end of String2.