t3chb0t
t3chb0t

Reputation: 18646

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

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.

Upvotes: 1

Views: 57

Answers (1)

nu11p01n73R
nu11p01n73R

Reputation: 26667

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

Upvotes: 1

Related Questions