[英]Optional characters in a regex
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: 有效字符串:
Invalid: 无效:
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: 这是一个Python测试脚本:
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
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.)
(看起来它可能有很多回溯。但另一方面,它没有+或*包含在另一个+或*中,我也不喜欢。)
^([+-]*[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+-]+
I like the 我喜欢
^(?=.*\d)[\d+-]+$
solution, myself. 解决方案,我自己 It says exactly what you need without requiring any head-scratching.
它确切地说明了你需要什么,而不需要任何头部刮伤。
I'd do it like this: 我这样做:
^[-+]*\d[\d+-]*$
Fast is good! 快很好!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.