user6914610
user6914610

Reputation:

Evalute number using regex

I have a regex to evalute numbers

^\d*(?:,\d+)*(?:.\d+)?

These are some numbers to check it

12345 -- correct

.123 -- correct

23,456,789.123 --correct

123.456.7 -- wrong

  1. -- wrong

12345, -- wrong

123., -- wrong

,123 -- correct

but this last test case should be wrong. It should not be correct. Any help is accepted thank you

Upvotes: 0

Views: 54

Answers (3)

The fourth bird
The fourth bird

Reputation: 163217

Your regex ^\d*(?:,\d+)*(?:.\d+)? matches the last case because it matches from the beginning of the string ^ a digit zero or more times \d*. After that you match a comma followed by one or more digits. (?:,\d+)*.

This comma would match the comma at the beginning because of the zero or more digits before it.

In the last group (?:.\d+)? I think you should escape the dot (?:\.\d+)? or else it would match any character

You could update your regex to match an optional dot \.? at the start followed by one or more digits \d+ and at the end add $ to assert the end of the line.

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

Explanation

^      # The beginning of the string
\.?    # Match an optional dot
\d+    # Match one or more digits
(?:    # A non capturing group
  ,\d+ # Match a comma and one or more digits
)*     # Close non capturing group and repeat zero or more times
(?:    # A non capturing group
  \.\d+ # Match a dot and one or more digits
)?     # Close optional group and make it optional
$      # The end of the string

Upvotes: 0

ctwheels
ctwheels

Reputation: 22817

See regex in use here

^(?!$)(?:\d{1,3}(?:,\d{3})*|\d+)?(?:\.\d+)?$
  • ^ Assert position at the start of the line
  • (?!$) Negative lookahead ensuring it's not also the end of the string (ensures at least one character exists)
  • (?:\d{1,3}(?:,\d{3})*|\d+)? Optionally match either of the following options
    • \d{1,3}(?:,\d{3})*
      • \d{1,3} Match any digit one to three times
      • (?:,\d{3})* Match {a comma followed by 3 digits} any number of times
    • \d+ Match one or more digits
  • (?:\.\d+)? Optionally match a decimal: dot . followed by one or more digits
  • $ Assert position at the end of the line

Upvotes: 0

Gurmanjot Singh
Gurmanjot Singh

Reputation: 10360

Try this regex:

^(?!,|$)\d*(?:,\d+)*(?:\.\d+)?$

Click for Demo

Explanation:

  • ^ - asserts the start of the line
  • (?!,|$) - negative lookahead to make sure that the current position is not followed by either a , or end of the line
  • \d* - matches 0+ occurrences of a digit
  • (?:,\d+)* - matches 0+ occurrences of (a , followed by 1+ digits)
  • (?:\.\d+)? - matches a . followed by 1+ occurrences of a digit. ? at the end makes this sub-sequence optional
  • $ - asserts the end of the line

Upvotes: 3

Related Questions