RegEx为5位数字拉链或空 [英] RegEx for 5 digit zip or empty

查看:75
本文介绍了RegEx为5位数字拉链或空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

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

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


推荐答案

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

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

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

请注意,除非你打算做除了证明它们存在以外的5位数的东西,你可以使用非捕获组(?:)来节省一点资源。

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.

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

这篇关于RegEx为5位数字拉链或空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆