Home > Mobile >  Regex : number decimal positive or negatif only
Regex : number decimal positive or negatif only

Time:01-27

i will test multiple regex but it's not working.

i want a regex for : number decimal positive and negative only. test value :

  1. 1 => ok
  2. 1.2 => ok
  3. -1 => ok
  4. -2.1 => ok a => nok
  5. 1.a => nok
  6. --1 nok

i use this regex [^\d \.?\d*$]/g decimal positive ok

but use with negative , i test with /[^[-]?\d \.?\d*$]/g not work

thans for help

CodePudding user response:

This is a regular expression to do what you need:

^-?\d (\.\d )?$

Let me break it down for you.

The ^ at the beginning says "start matching at the beginning of my input" and the $ at the end means "finish matching at the end of my input". If you don't add these, it can (depending on the API) match only parts of your input (like "-1" in "--1", which we don't want).

To account for negative numbers, we have -?. This means "the MIGHT be a - at the beginning of our input". The ? matches the character before it 0 or 1 times.

Next we use \d to say "match a digit" and the means "match the character before it 1 or more times". Combined, \d means "match 1 or more digits".

Now we have to account for the decimal place and after it. This may or may not actually exist, so we need to wrap the whole section in ()? to say "whatever is in these parentheses may or may not exist, but match it if it does. So in the parentheses, we have \.\d to say "match a literal . character, then one or more digits, like before.

You can test it here.

This answers your current question, but you may want to do more research on how regular expressions work. Here's an interactive tutorial that I'd suggest you go through: https://regexone.com/. For testing regular expressions interactively and have them explained to you, you can also use this: https://regex101.com/.

Hope this helps and good luck.

CodePudding user response:

The regex I propose is this:

(^|(?<=\s))-?\d ((?=\s )|(\.\d ))

You can test it here.

It looks for an optional minus. The minus must be either at the beginning of the line (^), or after a white space (a look-behind).

Then it looks for a sequence of digits.

Then it looks for:

  • either white space (end of number) - using a look-ahead
  • or the fractional part of the number.

Edit: I updated the regex101 example to show that the regex I proposed finds proper numbers (according to the requirements) even in the middle of text, not only when provided one-by-one.

  • Related