rnrneverdies
rnrneverdies

Reputation: 15657

Regex group generates empty matches among wanted matches

I'm trying to learn regex. I've created this /(\d?\.?\d?)/g to extract all numbers in a comma separated list of float numbers. like this:

1,2.2,3,4,5,6,7,8,9,10

https://regex101.com/r/aJ3eF2/2

But this pattern generates empty matches among wanted matches.

MATCH 1
1.  [0-1]   `1`
MATCH 2
1.  [1-1]   ``
MATCH 3
1.  [2-5]   `2.2`
MATCH 4
1.  [5-5]   ``

I want to understand why this happens? and how to fix it.

Upvotes: 1

Views: 39

Answers (2)

PM 77-1
PM 77-1

Reputation: 13334

If you do not expect something like .001 use (\d+\.?\d+)

Link: https://regex101.com/r/pX7rL1/1

Upvotes: 1

anubhava
anubhava

Reputation: 785491

You should use this regex to fix this behavior:

(\d+(?:\.\d+)?)

or better using word boundaries:

(\b\d+(?:\.\d+)?\b)

RegEx Demo

Your regex is giving empty matches because your regex (\d?\.?\d?) has everything optional i.e. a digit and decimal point and digit following it. Also you need to use quantifier + to make it match more than one digit on either side of decimal point.

(?:...) make it a non-capturing group.

Upvotes: 1

Related Questions