简体   繁体   English

正则表达式允许数字范围,或为null

[英]Regular expression to allow range of numbers, or null

I have the following Regular Expression, how can I modify it to also allow null? 我有以下正则表达式,如何修改它也允许null?

[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 谢谢

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. 是“或”运算符,字符串null与单词null匹配。 Thus it can be read out as <your previous pattern> or 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. 也就是说,例如, Matcher.matches()为空输入字符串返回true。 If that's what you're after, you could get away with using the above regexp and matching not on str but on ""+str which would result in "null" if str actually equals null . 如果这就是你所追求的, 你可以使用上面的正则表达式并且不匹配str但是匹配""+str ,如果str实际上等于null ,则会导致"null"

如果为null,则表示空字符串,您需要:

^(?:[0-9]{5}|[0-9]{10}|)$
[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 entire string 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}|)$

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM