javascript 5 位 zip 或空的 RegEx

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11127515/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 12:08:50  来源:igfitidea点击:

RegEx for 5 digit zip or empty

javascriptregex

提问by Registered User

I have this regex that checks for a 5 digit number ^\d{5}$

我有这个正则表达式可以检查 5 位数字 ^\d{5}$

How do I change it so that it returns true also for an empty string?

如何更改它以便它也为空字符串返回 true?

<script type="text/javascript">
var regex = /^\d{5}$/;

alert(regex.test(12345));
alert(regex.test(''));
</script>

回答by Michael Berkowski

Enclose it in ()and add a ?to make the entire pattern optional. Effectively, you are then either matching ^\d{5}$OR ^$(an empty string).

将其括起来()并添加 a?以使整个模式可选。实际上,您要么匹配^\d{5}$OR ^$(空字符串)。

var regex = /^(\d{5})?$/;

console.log(regex.test(12345));
console.log(regex.test(''));
// true
// true

// Too long, too short
console.log(regex.test(123456));
console.log(regex.test('1'));
// false
// false

Note that unless you intend to do something with the 5 digits other than prove they are present, you can use a non-capturing group (?: )to save a tiny bit of resources.

请注意,除非您打算对这 5 位数字做一些事情而不是证明它们存在,否则您可以使用非捕获组(?: )来节省一点资源。

var regex = /^(?:\d{5})?$/;