Java 正则表达式以允许数字范围,或为空
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3422638/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Regular expression to allow range of numbers, or null
提问by Jimmy
I have the following Regular Expression, how can I modify it to also allow null?
我有以下正则表达式,如何修改它以允许空值?
[0-9]{5}|[0-9]{10}
[0-9]{5}|[0-9]{10}
I would like it to allow a 5 digit number, a 10 digit number, or null
我希望它允许 5 位数字、10 位数字或 null
Thanks
谢谢
采纳答案by Jez
If by null you mean the empty string, you want:
如果 null 表示空字符串,则需要:
^(?:[0-9]{5}|[0-9]{10}|)$
回答by Tim Pietzcker
[0-9]{5}|[0-9]{10}|null
should do it. Depending on how you are using the regex, you might need to anchor it in order to be sure that it will always match the entirestring and not just a five-digit substring inside an eight-digit string:
应该这样做。根据您使用正则表达式的方式,您可能需要锚定它以确保它始终匹配整个字符串,而不仅仅是八位字符串中的五位子字符串:
^(?:[0-9]{5}|[0-9]{10}|null)$
^
and $
anchor the regex, (?:...)
is a non-capturing group that contains the alternation.
^
并$
锚定正则表达式,(?:...)
是一个包含交替的非捕获组。
Edit: If you mean null
=="empty string", then use
编辑:如果您的意思是null
==“空字符串”,则使用
^(?:[0-9]{5}|[0-9]{10}|)$
回答by aioobe
Just append |null
:
只需附加|null
:
[0-9]{5}|[0-9]{10}|null
As you probably know, |
is the "or" operator, and the string of characters null
match the word null. Thus it can be read out as <your previous pattern> or null
.
您可能知道,|
是“或”运算符,字符串null
与单词 null 匹配。因此它可以读出为<your previous pattern> or null
。
If you want the pattern to match the null-string, the answer is that it's impossible. That is, there is no way you can make, for instance, Matcher.matches()
return true for a null input string. If that's what you're after, you could get away withusing the above regexp and matching not on str
but on ""+str
which would result in "null"
if str
actually equals null
.
如果您希望模式匹配空字符串,答案是不可能的。也就是说,例如,您无法Matcher.matches()
为空输入字符串返回 true。如果这就是你所追求的,你可以逃避使用上面的正则表达式并匹配 not on str
but on ""+str
which 会导致"null"
ifstr
实际上等于null
。