Regex for getting the first occurring matching pair
Given that you can reference a capture group in a regex pattern, is it
possible to use said capture group in a lookbehind?
if you have the string
"monkeys eat bananas, bananas are terrified of monkeys"
bananas is the first matched pair, while monkeys is the first word that
has a match. I can get monkeys without any issue
(\w+).*\1 # returns monkeys
But if I want to get the word which matches first I would need to be able
to do something like this
(?<=\1)(\w+)
However, this fails, and I would guess for the simple reason that when the
lookbehind is evaluated, \1 means nothing. Is there some more regex magic
that I have not come across yet, that would allow me to match something
like this?
No comments:
Post a Comment