Regex For Numeric Fields

Asked

Viewed 164 times

-5

I need a regex that validates numbers, commas, and period it must contain numbers and if it contains a point or comma, have only one of the two, and only once

1.1 - true
1,2 - true
2 - true
1..2 - false
1.2. - false
1,2.2 - false
2,3,2 - false
-2 - false
,2 - false
2, - false

with that expression '/[ 0-9,. ]/g' it blocks anything that is not number of dots or commas, but you can put as many as you want (the dots and commas).

  • 3

    Ok. What did you do? What was the result obtained? Do you know how to elaborate a regular expression?

  • I need a regex q do this, I know only the basics about preparing regex.

  • 2

    Then check with the basics you have and try to do it first. If you want to test, I recommend using sites like https://regex101.com/. If you still can’t, you can come back here and [Edit] the question, adding your attempt and what the result was. I also recommend that you add all possible cases to your description as it is not clear whether ,1 would be a valid value (even having numbers and only a comma), or 1,.

1 answer

0

When asked a question here, we’re supposed to have something to guide us. Still, I think this is the solution. Digits from 1 to 9 followed by a semicolon with 1 number or more as decimals.

^[1-9]\d*(,\d+)?$   ----> para ,
^[1-9]\d*(\.\d+)?$  ----> para .

Browser other questions tagged

You are not signed in. Login or sign up in order to post.