Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby Regex non-greedy match: looking for the closest occurrence of a phrase left to a searched word

Tags:

regex

ruby

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/miand 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?

like image 531
benams Avatar asked Feb 09 '14 12:02

benams


1 Answers

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
like image 113
Tim Pietzcker Avatar answered Oct 20 '22 01:10

Tim Pietzcker