Reputation: 1600
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?
Upvotes: 2
Views: 5363
Reputation: 2306
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.
Upvotes: 1
Reputation: 4766
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]+)
Upvotes: 3
Reputation: 174696
Use the below regex and get the string you want from group index 1.
\d+\s+(.*?)\s+[A-Z]+
Upvotes: 4