Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional characters in a regex

Tags:

regex

optional

The task is pretty simple, but I've not been able to come up with a good solution yet: a string can contain numbers, dashes and pluses, or only numbers.

^[0-9+-]+$

does most of what I need, except when a user enters garbage like "+-+--+"

I've not had luck with regular lookahead, since the dashes and pluses could potentially be anywhere in the string.

Valid strings:

  1. 234654
  2. 24-3+-2
  3. -234
  4. 25485+

Invalid:

  1. ++--+
like image 705
Martin Avatar asked May 19 '09 17:05

Martin


1 Answers

How about this:

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

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

Here's a Python test script:

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
like image 162
RichieHindle Avatar answered Sep 21 '22 06:09

RichieHindle