pcre - Regex not returning all matches -


i have following regex (my actual regex lot more complex pinned down problem this): \s(?<number>123|456)\s

and following test data:

" 123 456 "

as expected/wanted result have regex match in 2 matches 1 "number" being "123" , second number being "456". however, i'm getting 1 match "number" being "123".

i did notice adding space in between "123" en "456" in test data give 2 matches...

why don't result want? how right?

your pattern contains consuming \s patterns matches whitespace before , after number, , input contains consecutive numbers separated single whitespace. if there 2 spaces between numbers, work.

use whitespace boundaries based on lookarounds:

(?<!\s)(?<number>123|456)(?!\s) 

see regex demo

the (?<!\s) negative lookbehind fail match if there non-whitespace char left of current location, , (?!\s) negative lookahead fail match if there non-whitespace char right of current location.

(?<!\s) same (?<=^|\s) , (?!\s) same (?=$|\s), more efficient.

note in many situations might go 1 lookahead , use

\s(?<number>123|456)(?!\s) 

it ensure consecutive whitespace separated matches found.


Comments

Popular posts from this blog

python - Selenium remoteWebDriver (& SauceLabs) Firefox moseMoveTo action exception -

html - How to custom Bootstrap grid height? -

transpose - Maple isnt executing function but prints function term -