简体   繁体   中英

Regex simultaneous lookahead and lookbehind

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

Eg:

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 : [AZ]+

How can I accomplish that?

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

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

DEMO

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 (?= [AZ]+)

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM