Search code examples
regex

Match until last occurrence of, but if not exists - match to end of string


I'm trying to construct a regex to match a part of a string, starting from a certain string, and until the last occurrence of a string, unless that string doesn't exist - in which case the rest of the string should match.

Some inputs I'm trying to match:

i_123_Mobile
i_123_abc_Mobile
i_123aa_abcdaeedg_Desktop
i_abc123

Expected output:

123
123_abc
123aa_abcdaeedg
abc123

The following regex works for the first three, but not for the fourth (Demo):

(?<=i_).*(?=_)

Although I can just use an | operator:

(?<=i_).*(?=_)|(?<=i_).*$

I'd like to learn if there's a way to not repeat myself (note the (?<=i_) repeats)?


Solution

  • You can combine your two alternatives after the one element that would be repeated:

    (?<=i_)(?:.*(?=_)|.*$)
    

    Demo

    Or without the lookahead works too if you don't mind the trailing _ as part of the match:

    (?<=i_)(?:.*_|.*$)
    

    Demo