Optional Regular Expression Characters

The task is quite simple, but I have not yet been able to find a good solution: a line can contain numbers, dashes and pluses, or only numbers.

^[0-9+-]+$ 

does most of what I need, except when the user enters garbage, for example "+ - + - +"

I was not lucky with regular viewing, as dashes and pluses could potentially be anywhere on the line.

Valid strings:

  • 234654
  • 24-3 + -2
  • -234
  • 25485 +

Invalid:

  • ++ - +
+6
regex optional
source share
5 answers

What about:

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

This ensures that there is at least one digit in the string. (It looks like he might have a lot of digressions, but on the other hand, he doesn't have + or * wrapped inside another + or *, which I don't like either.)

+8
source share

How about this:

 ([+-]?\d[+-]?)+ 

which means "one or more digits, each of which may be preceded or followed by an additional plus or minus."

Here's a Python script test:

 import re TESTS = "234654 24-3+-2 -234 25485+ ++--+".split() for test in TESTS: print test, ":", re.match(r'([+-]?\d[+-]?)+', test) is not None 

which prints this:

 234654 : True 24-3+-2 : True -234 : True 25485+ : True ++--+ : False 
+15
source share
 ^([+-]*[0-9]+[+-]*)+$ 

Another solution, using a positive view of the statement, ensuring the availability of a single number.

 ^[0-9+-]+$(?<=[0-9][+-]*) 

Or using a positive statement ahead.

 (?=[+-]*[0-9])^[0-9+-]+ 
+2
source share

I like

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

I myself. He says exactly what you need without requiring any scratches on your head.

0
source share

I would do it like this:

 ^[-+]*\d[\d+-]*$ 

Fast is good!

0
source share