Andreas Hunter
Andreas Hunter

Reputation: 5004

How to match correctly only needed numbers type

I have custom string:

Code: 12345
Price: $4900,50

And two regex for match numbers:

  1. Regex for match numbers with fixed length: /[0-9]{4,6}/mg
  2. Regex for match float numbers: /\d+(?:[.,]\d+)?/mg

1th regex must match only 12345 in this case but it's found also 4900 which is not needed.

Demo 1th regex: https://regex101.com/r/jnhsly/2

2th regex must much only float number from string. In this example string must found only 4900,50 but it's also found 12345 which is not needed result.

Demo 2th regex: https://regex101.com/r/If9y6G/1

How I can find only needed results in both regex in my case?

Upvotes: 0

Views: 31

Answers (2)

anubhava
anubhava

Reputation: 784938

For case 1 of integer numbers only, you may use this regex:

(?<![\d.,])\d{4,6}\b(?![.,]\d)
  • (?<![\d.,]): Make sure that we don't have a digit or , or . at previous position
  • \b: Word boundary
  • (?![.,]\d): Make sure that we don't have a , or . followed by a digit at next position

RegEx Demo 1

For case 2 of float numbers, you may use this regex:

\d+[.,]\d+

There is no need to make [.,]\d+ optional since you are only matching floating point numbers here.

RegEx Demo 2

Upvotes: 2

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626690

To match int numbers containing 4 to 6 digits, you need to use

(?<!\d)(?<!\d[.,])\d{4,6}(?![,.]?\d)

See the regex demo

Details

  • (?<!\d) - no digit allowed immediately on the left
  • (?<!\d[.,]) - no digit and . or , is allowed immediately on the left
  • \d{4,6} - four, five or six digits
  • (?![,.]?\d) - no optional , or . and a digit allowed immediately on the right.

The \d+(?:[.,]\d+)? pattern matches either integer or float values because the non-capturing group is optional thanks to the ? quantifier, remove it. The whole non-capturing group will be redundant then, that is why the pattern to match float values will become \d+[.,]\d+.

Upvotes: 1

Related Questions