Lets say I have the following string: "BENffew123X\r\nBENx432f456X\r\nBEN!233789X\r\nBEN4545789X"
I want to have a regex that will catch "BEN!233789", it has to lookup non-greedily for "BEN", followed by any character (excluding the word "BEN") and ending with 789X. I tried the regex: /BEN.+?789X/mi
and I get "BENffew123X\r\nBENx432f456X\r\nBEN!233789X"
as a match.
I understand that this regex looks for the first "BEN" and catches the start of the string, but I want it to look for the "BEN" which is closest to the first "789X". How can I achieve that? One Idea is to reverse the string, should I do it?
You need to make sure that BEN
isn't present in the text between BEN
and 789X
. You can do this using a negative lookahead assertion:
/BEN(?:(?!BEN).)*?789X/mi
See it live on regex101.com.
Explanation:
BEN # Match "BEN"
(?: # Start of non-capturing group that matches...
(?!BEN) # (if "BEN" can't be matched here)
. # any character
)*? # Repeat any number of times, as few as possible
789X # Match 789X
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With