1

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 meat 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?

4
  • What is your regex flavor?
    – anubhava
    Nov 6, 2016 at 15:34
  • Only the last match i.e. String3 will be available in your 2nd capturing group.
    – anubhava
    Nov 6, 2016 at 15:35
  • @anubhava i actually dont know, i'm doing it with php.
    – PlayMa256
    Nov 6, 2016 at 15:45
  • ok PHP is PCRE and \G is supported to my answer should work.
    – anubhava
    Nov 6, 2016 at 15:48

1 Answer 1

1

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.

2
  • Could you explain me this: (?<!^)\G\`. I couldnt understand what it really does.
    – PlayMa256
    Nov 6, 2016 at 16:07
  • \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.
    – anubhava
    Nov 6, 2016 at 16:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.