正则表达式匹配特定长度的数字 [英] Regex to match digits of specific length

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

问题描述

我希望匹配 15 位数字(作为较大正则表达式字符串的一部分).现在,我有

I am looking to match a 15 digit number (as part of a larger regex string). Right now, I have

\d\d\d\d\d\d\d\d\d\d\d\d\d\d\d

但我觉得必须有一种更简洁的方法来做到这一点.

but I feel like there must be a cleaner way to do this.

推荐答案

如果您的正则表达式语言与 Perl 兼容:\d{15}.

If your regex language is Perl-compatible: \d{15}.

在不知道将使用此代码段的外部上下文的情况下,很难说如何处理边缘(这样您就不会意外抓取额外的数字).明确的独立于上下文的解决方案是这样的:

It is difficult to say how handle the edges (so you don't accidentally grab extra digits) without knowing the outer context in which this snippet will be used. The definitive context-independent solution is this:

(?<!\d)\d{15}(?!\d)

你可以把它放在任何正则表达式的中间,它会匹配(并且只匹配)一个 15 位数字的序列.然而,这很尴尬,而且通常是不必要的.假设非字母数字边界(例如,数字周围的空格)的更简单版本是这样的:

You can put this in the middle of any regex and it will match (and only match) a sequence of exactly 15 digits. It is, however, quite awkward, and usually unnecessary. A simpler version that assumes non-alphanumeric boundaries (e.g., whitespace around the digits) is this:

\b\d{15}\b

但是,如果字母紧跟在序列之前或之后,它将不起作用.

But it won't work if the letters immediately precede or followed the sequence.

这篇关于正则表达式匹配特定长度的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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