Ellone
Ellone

Reputation: 3898

Regex for numbers only allowing spaces and 1 comma or dot

I'm struggling to make a regex matching the following conditions :

This should match strings such as : 4564654, 4 454 845 484, 874584.42, 42 424 484.45, 874584,42, 42 424 484,45...

And not match 42a, 42.45,42...

I tried to expand this one : ^[0-9[,.!?]*$ but I'm not succeeding.

Upvotes: 1

Views: 3125

Answers (4)

The fourth bird
The fourth bird

Reputation: 163632

You could use a character class to match either a dot or a comma followed by 1+ digits in an optional group:

^\d+(?:[,.]\d+)?(?: \d+(?:[,.]\d+)?)*$

That will match

  • ^ Start of the string
  • \d+(?:[,.]\d+)? Match 1+ digits with an optional part to match either a dot or a comma followed by 1+ digits
  • (?: \d+(?:[,.]\d+)?)* repeat the previous part 0+ times with a space at the start
  • $ End of the string

Regex demo

Update

If the string can only contain a single dot or comma:

^(?!(?:[^.,\n]*[.,]){2})\d+(?:[,.]\d+)?(?:[^\S\n\r]\d+(?:[,.]\d+)?)*$
  • ^ Start of the string
  • (?!(?:[^.,\n]*[.,]){2}) Negative lookahead, assert what is on the right is not 2 times a dot or comma
  • \d+(?:[,.]\d+)? Match 1+ digits, optionally match a dot or comma and 1+ digits
  • (?: Non capturing group
    • [^\S\n\r] Negated character class, not match a non-whitespace char and not match a newline
    • \d+(?:[,.]\d+)? Match 1+ digits, optionally match a dot or comma and 1+ digits
    • )* Close non capturing group and repeat 0+ times
  • $ End of the string

Regex demo

let regex = /^(?!(?:[^.,\n]*[.,]){2})\d+(?:[,.]\d+)?(?:[^\S\n\r]\d+(?:[,.]\d+)?)*$/;
[
  "424242424",
  "424242.424",
  "454545.58",
  "4545454,4545",
  "45454,45",
  "4 45 44454.45",
  "4 454 454,45",
  "1 2 3",
  "1 2 3",
  "4,2 424 484,45 34.4 3 4",
  "545g45",
  "454.454.45",
  "45454,454,45",
  "45.44,45",
  "45,45.45",
  "4 4545 4545 45  45",
].forEach(s => console.log(s + ": " + regex.test(s)))

Upvotes: 3

user11410750
user11410750

Reputation: 1

Use this ^(\d*? ?\d)+(,|\.)?\d+$

test cases https://regex101.com/r/DDdvf3/4

Upvotes: 0

mbojko
mbojko

Reputation: 14699

Some digits or spaces first:

^[0-9 ]*

then, a comma or a point:

(\.|,)?

Then, some more digits and/or spaces, and the end of the expression:

[0-9 ]*$

Together:

^[0-9 ]*(.|,)?[0-9 ]*$

Upvotes: 0

Pushpesh Kumar Rajwanshi
Pushpesh Kumar Rajwanshi

Reputation: 18357

You can use this regex,

^(?=^[\d ]+[,.]?[\d ]+$)\d+(?:[ .,]\d+)*$

Here, (?=^[\d ]+[,.]?[\d ]+$) positive look ahead ensures, that there is only one comma or dot present while \d+(?:[ .,]\d+)* takes care of the format and allowed characters.

Regex Demo

Upvotes: 1

Related Questions