Skip to main content
 首页 » 编程设计

Python 正则表达式匹配任何恰好包含 n 位数字的单词,但也可以包含其他字符

2025年05月04日24xiaohuochai

例如如果 n=10,则正则表达式:

应该匹配:

(123)456-7890 
(123)456-(7890) 
a1b2c3ddd4e5ff6g7h8i9jj0k 

但不应该匹配:

(123)456-789 
(123)456-(78901) 
etc. 

注意:我正在严格寻找正则表达式,这是一个硬约束。

======================================

编辑:其他约束

我正在寻找以下形式的解决方案:

regex = re.compile(r'?????????') 

哪里:

regex.findall(s) 

... 为 ['(123)456-7890','(123)456-(7890)', 'a1b2c3ddd4e5ff6g7h8i9jj0k'] 中的 s 返回一个非空数组

并为 ['(123)456-789', '(123)456-(78901)'] 中的 s 返回一个空数组

请您参考如下方法:

正则表达式 ^\D*\d\D*\d\D*\d\D*\d\D*\d\D*\d\D*\d\D*\d\D*\d\D*\d\D*$ 将找到所有匹配项。将其更改为适用于 n 数字使用 "^"+"\D*\d"*n+"\D*$"

import re 
 
n=10 
regex = "^"+"\D*\d"*n+"\D*$" 
 
numbers='''(123)456-7890 
(123)456-(7890) 
a1b2c3ddd4e5ff6g7h8i9jj0k 
 
 
(123)456-789 
(123)456-(78901)''' 
 
matches=re.findall(regex,numbers,re.M) 
 
print(matches) 

或者单场比赛

pattern = re.compile("^"+"\D*\d"*n+"\D*$") 
print(pattern.match('(123)456-7890').group(0)) #(123)456-7890 or AttributeError if no match so wrap in try except