正则表达式匹配以测试有效年份 [英] Regular Expression Match to test for a valid year

查看:61
本文介绍了正则表达式匹配以测试有效年份的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个值,我想验证它以检查它是否为有效年份.我的标准很简单,其中值应该是一个带有 4 字符的整数.我知道这不是最好的解决方案,因为它不允许 1000 之前的年份,并且允许诸如 5000 之类的年份.这个标准足以满足我目前的情况.

Given a value I want to validate it to check if it is a valid year. My criteria is simple where the value should be an integer with 4 characters. I know this is not the best solution as it will not allow years before 1000 and will allow years such as 5000. This criteria is adequate for my current scenario.

我想到的是

\d{4}$

虽然这有效,但它也允许负值.

While this works it also allows negative values.

如何确保只允许使用正整数?

How do I ensure that only positive integers are allowed?

推荐答案

需要添加一个起始锚^为:

You need to add a start anchor ^ as:

^\d{4}$

您的正则表达式 \d{4}$ 将匹配以 4 位数字结尾的字符串.所以像 -1234 这样的输入将被接受.

Your regex \d{4}$ will match strings that end with 4 digits. So input like -1234 will be accepted.

通过添加起始​​锚点,您只匹配那些开始和结束 4 位数字的字符串,这实际上意味着它们必须只包含 4 位数字.

By adding the start anchor you match only those strings that begin and end with 4 digits, which effectively means they must contain only 4 digits.

这篇关于正则表达式匹配以测试有效年份的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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