Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex Grouping with Repeat Operators

I am using groups to try to match on a certain pattern, and am not getting quite the results I expect. The pattern of interest are as follows:

([0-9]+(\.[0-9]+)+)

For string 1.23, I get $1=1.23, and $2=.23 which makes sense to me.

But for string 1.2.3, I get $1=1.2.3 and $2=.3, where I would expect $2=.2.3, because its group is a decimal point and a digit, repeated.

Can someone please explain to me how this works? Thank you!

like image 286
prelic Avatar asked Jan 25 '26 06:01

prelic


2 Answers

When you use capturing groups with a quantifier, only the last repetition of the captured pattern will be stored.

like image 194
Hunter McMillen Avatar answered Jan 27 '26 23:01

Hunter McMillen


"These pattern match variables are scalars and, as such, will only hold a single value. That value is whatever the capturing parentheses matched last."

http://blogs.perl.org/users/sirhc/2012/05/repeated-capturing-and-parsing.html

In you example, $1 matches 1.2.3. As the pattern repeats, $2 would be set to .2 until the final match of .3

like image 22
fugu Avatar answered Jan 27 '26 23:01

fugu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!