regex-group

REGEX fails when adding an optional mark to a group


In the following string blah blahTESTblab la14blah-15S rebla I'm trying to capture TEST and 15S if present.

I wrote the following regex : (TEST).*?(\d{1,2}S)?

Everything is going well until the last ?. The last group really needs to be optional. And groups can't be anchored, as strings I'm searching in are human written, ie tot reliable.

What's wrong ?


Solution

  • The following pattern seems to do what you want:

    (TEST)(?:.*?(\d{1,2}S)|)
    

    This says to match:

    Demo