Optional characters in a regex

你。 提交于 2020-01-03 09:05:13

问题


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. ++--+

回答1:


How about:

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

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




回答2:


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



回答3:


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

Another solution using a positive look behind assertion ensuring there is at leat one number.

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

Or using a positive look ahead assertion.

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



回答4:


I like the

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

solution, myself. It says exactly what you need without requiring any head-scratching.




回答5:


I'd do it like this:

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

Fast is good!



来源:https://stackoverflow.com/questions/884014/optional-characters-in-a-regex

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!