Ruby Regex non-greedy match: search for the closest occurrence of the phrase remaining before the searched word

Suppose I have the following line: "BENffew123X\r\nBENx432f456X\r\nBEN!233789X\r\nBEN4545789X" I want a regular expression that will catch "BEN! 233789", it should look 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 regular expression searches for the first β€œBEN” and catches the beginning of the line, but I want it to look for β€œBEN”, which is closest to the first β€œ789X”. How can i achieve this? One idea is to flip a line, should I do this?

+7
ruby regex
source share
1 answer

You need to make sure that BEN not in the text between BEN and 789X . You can do this using a negative statement pending :

 /BEN(?:(?!BEN).)*?789X/mi 

See 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 
+12
source share

All Articles