Python 正则表达式匹配特定长度的数字

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

Regex to match digits of specific length

pythonregex

提问by MrGlass

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

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

\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.

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

采纳答案by Marcelo Cantos

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

如果您正则表达式语言是Perl兼容的:\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)

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:

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

\b\d{15}\b

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

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

回答by paxdiablo

You can generally do ranges as follows:

您通常可以按如下方式执行范围:

\d{4,7}

which means a minimum of 4 and maximum of 7 digits. For your particular case, you can use the one-argument variant, \d{15}.

这意味着最少 4 位,最多 7 位数字。对于您的特定情况,您可以使用单参数变体\d{15}.

Both of these forms are supported in Python's regular expressions- look for the text {m,n}at that link.

Python 的正则表达式支持这两种形式-{m,n}在该链接中查找文本。

And keep in mind that \d{15}will match fifteen digits anywhere in the line, including a 400-digit number. If you want to ensure it only has the fifteen, you use something like:

请记住,这\d{15}将匹配行中任何位置的 15 位数字,包括 400 位数字。如果你想确保它只有十五个,你可以使用类似的东西:

^\d{15}$

which uses the start and end anchors, or

使用开始和结束锚点,或

^\D*\d{15}\D*$

which allows arbitrary non-digits on either side.

这允许任意一侧的非数字。

回答by FeLiX StEpHeN

There, are two ways i have, to limit numbers.

我有两种方法来限制数字。

using len,

使用len

num = 1234
len(str(num)) <= 4

This output will be True / False.

此输出将为真/假。

using regular expression,

使用正则表达式

import re
num = 12324
re.match(r'(?:(?<!\d)\d{4}(?!\d))', str(num))

The output will be regular expression object or None.

输出将是正则表达式对象或无。