Home > Mobile >  RegEx greedy quantifier not working correctly
RegEx greedy quantifier not working correctly

Time:01-18

I made this little RegEx to find decimal number in a string but my quantifier does something that I can’t explain.

Here is my regular expression :

(?: *\d{1,3})*,\d{2}

And an example of what it is matching (with ** highlights to indicate the match):

2000 1 142,94 1 142,94

And what it should match :

2000 1 142,94 1 141,94

The format for the group separator is a space, e.g. 1 000 000,00

The problem here, is that my re matches with the 2000 at the start of the example.

I tried to use a visualizer to verify my way of thinking but it seemed correct for me. Am I missing something?

CodePudding user response:

Your regular expression says zero or more spaces, followed by one to three digits, which obviously matches the initial 200. Then you allow a repetition with zero spaces and, for example, one more digit. That's what "greedy" means; the regex engine will do its darndest to find a string which matches the pattern you gave it.

Apparently your real requirement is to find numbers with groups of three digits, is that correct?

(?:\d{1,3}( \d{3})*)?,\d{2}

This will require one to three digits, then zero or more groups with a space and three more digits, followed by the decimal comma and two decimal digits.

Your original attempt permitted ,12 so I have preserved that requirement; if you actually want to permit a number with optional decimals, perhaps instead go with

\d{1,3}( \d{3})*(?:,\d{2})?

CodePudding user response:

Your question isn't quite clear. I thought you want to extract decimal numbers from a string.

I used this regex to detect numbers with max three decimal. (eg. 123,234 or 123,23). And I also add both comma & dot point (, & .) as decimal separator.I put it inside group () to extract easily.

(\d{1,3}[,\.]\d{1,3})

Here's regex101 link that I tested - https://regex101.com/r/po6Rqr/1

  •  Tags:  
  • Related