I am trying to match the first instance of a word after a certain word has been listed. There could be whitespace and many lines.
Here is an example of desired outcomes with the requirement of the word "before" coming before the word "after" and then only matching the first instance.
beforeafter - match
before after - match
beforeafterafter - matches only first after
beforeafter something after - matches only first after
before
(whitespace)
after - match
befafter -no match
before bar foo baz after - match
I believe I am close with this regex
(?<=(before([^after]*)))(after)
which utilizes a positive lookbehind.
But the [^after]
negates the characters in the set rather than the whole word itself (which leads to the final example above not matching).
It’s almost like I want a "positive look behind" (aka look for "before") and then between that and the word I desire, I want a negative look behind of my initial word (i.e. "after").
When I tried that, I also got something close but not quite: (?<=(before(.|s)*(?<!(after))))after
. This results in wrongly selecting an "after" that is not connected to the initial after.
3
Answers
You don’t need a regex for this. You can just use indexOf.
Here’s an example I found works using python:
Just use a positive look behind.
The key is to use
.*
afterbefore
and beforeafter
to allow any characters betweenbefore
andafter
. To allow this match white spaces also adds
flag to the regexp.The same task can be achieved with
String::indexOf()
which is 5x faster.