Home > Software engineering >  Regular expressions to check for sign
Regular expressions to check for sign

Time:01-19

I have written these regular expressions to check if there is a sign between the numbers. That is, every number entered must have a sign. (It does not matter where this sign is in the numbers, it can be the last, middle or first) But the problem is that if I do not add the sign to the numbers, I still will not get an error

^[0-9]*$|^[0-9]*[ ]{1}$|^[ ]{1}[0-9]*$|^[0-9]*[ ]{1}[0-9]*$

CodePudding user response:

Your first alternative allows only optional digits without any plus sign.

You can write the pattern as

^[0-9]*[ ]$|^[ ][0-9]*$|^[0-9]*[ ][0-9]*$

Or shorten it to

^\d*\ \d*$

Note that both pattern allow only a without any digits.

See a regex demo.

  •  Tags:  
  • Related