match groups of words and digits regex in any order -
match groups of words and digits regex in any order -
suppose have next string:
"7 apples , 13 oranges"
/(\d+).*?(apples)/i
the above regex match 7 apples if alternate order , numbers "45 oranges , 9 apples".it match first digit 45 rather digit corresponding apples, want.
how can write regex match , homecoming match groups of digits + apples if write sentence in next 2 orders:
"7 apples , 13 oranges" "13 oranges 52 apples"ie, i'd match 7 apples, match groups of 7 , apples , 52 apples match groups 52 , apples.
where got wrong in /(\d+).*?(apples)/i
?
.*?
though lazy matching matches digit next apple
which means string
"13 oranges 52 apples"
it matches 13
till apple
@ end of string, since .
matches anything
see link illustration : http://regex101.com/r/ul5ex0/2
how correct?since symbol seperating digit , apple space, can utilize \s
character instead of .
as
(\d+)\s(apples)
matches 7
, 52
seen in http://regex101.com/r/ul5ex0/3
for safe side can have
(\d+)\s+(apples)
any number of spaces between digit , apple
a word boundary \b
can used safety
regex
Comments
Post a Comment