Regex simultaneous lookahead and lookbehind

5.1k views Asked by At

I am trying to write a Regex that simultaneously matches pattern in the front and pattern in the back of my current character.

E.g.:

red, gree, yellow-white, snowy

in

312415 red, gree, yellow-white, snowy CDEFASE

one, two, three #four

in

29321093123 one, two, three #four IRUASJDJADALLDLA

As you can see, in front and in the back of the middle parts of the string I have the same pattern:

front: \d+

back: [A-Z]+

How can I accomplish that?

3

There are 3 answers

0
Avinash Raj On BEST ANSWER

Use the below regex and get the string you want from group index 1.

\d+\s+(.*?)\s+[A-Z]+

DEMO

2
Nick On

you can't do look behind and look ahead simultaneously, but you can use them separately the same way you would normally use them.

Start with a lookbehind that checks for a string a digits followed by a space (?<=\d+ ) Match any characters in the middle .+ Then end with a lookahead that matches a space followed by one or more letters (?= [A-Z]+)

Put it all together and you got (?<=\d+ ).+(?= [A-Z]+)

0
Farhad Alizadeh Noori On

Lookaheads and Lookbehinds are not what you think they are. They are zero-width assertions, meaning they do not match anything but only check the existence/non existence of a pattern.

What you want here is to match a number of digits followed by a series of characters that then follow another series of upper case characters. How can you capture the stuff in the middle? You can use brackets. They capture the match as they go through and save it for your later reference. The (.*?) part in AVinash's answer is the part that actually captures the text you want.