How to match a string before something or the end of line?

68 views Asked by At

I need to match the following string:

" 4/abc def"

from

" 4/abc def 5/abc"

or

" 4/abc def"

So far I managed to build this regex:

(?<MyGroup> 4\/(.+)(?=(?: \d\/)))

and I tried to make the lookahead optional ? or add a |$ but then it catches everything. Can I somehow make the 5/abc optional?

I've tried it with these expressions but they didn't work for both cases:

(?<MyGroup> 4\/(.+)(?=(?: \d\/)?))
(?<MyGroup> 4\/(.+)(?=(?: \d\/|$)))

SAMPLE

EDIT:

I am forced to use the period because there can by any character. It's a free-text field.

1

There are 1 answers

4
nu11p01n73R On BEST ANSWER

Make the .+ lazy by adding a ? and add the alternation to $

(?<MyGroup> 4\/(.+?)(?=(?: \d\/)|$))
  • (.+?) The lazy matching causes the regex engine to stop once it sees the first \d/ than continuing to the end of the string.

Regex Demo