正则表达式匹配未用数字括起来的 5 位子字符串 [英] Regex matching 5-digit substrings not enclosed with digits
本文介绍了正则表达式匹配未用数字括起来的 5 位子字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想从字符串中提取 5 个连续的数字
I want to extract 5 continuous digits from the string
我写的代码.
re.findall(r"((\D|^)*)\d\d\d\d\d((\D|$)*)", s)
但它不能传递字符串
"Helpdesk-Agenten (m/w) Kennziffer: 12966"
预期结果是:
12966
示例 2:
#input
"Helpdesk-Agenten (m/w) Kennziffer: 12966abc"
# expected
12966
示例 3:
#input
"Helpdesk-Agenten (m/w) Kennziffer: 12966345"
# expected
"" (because the length of continuous digits is longer than 5)
推荐答案
你当前的正则表达式 (((\D|^)*)\d\d\d\d\d((\D|$)*)
) 与 re.findall
一起使用不会返回数字块,因为它们没有被捕获.更多,(\D|^)*
和(\D|$)*
部分是可选,这意味着他们没有做他们应该做的事情,正则表达式会在更长的数字块中找到 5 位块.
Your current regex (((\D|^)*)\d\d\d\d\d((\D|$)*)
) used with re.findall
won't return the digit chunks because they are not captured. More, the (\D|^)*
and
(\D|$)*
parts are optional and that means they do not do what they are supposed to do, the regex will find 5 digit chunks inside longer digits chunks.
如果你必须找到没有被其他数字包围的5位数字块,使用
If you must find 5 digit chunk not enclosed with other digits, use
re.findall(r"(?<!\d)\d{5}(?!\d)", s)
查看正则表达式演示
详情:
(? - 当前位置之前不允许有数字
\d{5}
- 5 位数字(?!\d)
- 当前位置后不允许有数字.
(?<!\d)
- no digit is allowed before the current location\d{5}
- 5 digits(?!\d)
- no digit allowed after the current location.
这篇关于正则表达式匹配未用数字括起来的 5 位子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文