简体   繁体   English

仅匹配长度为 3 的整数

[英]Matching integers of length only 3

I am trying to find all the integers of length 3 without iterating,though they have leading zeros我试图在不迭代的情况下找到所有长度为 3 的整数,尽管它们有前导零

>>> import re
>>> li = re.findall("[\d+]{3}","abc42h456k678954hars234ok001")
>>> print(li)
['456', '678', '954', '234','001']

I want the regex to consider 678954 as a single integer of length 6 but not two individuals of length 3. Whats the proper way to do so it should replace the following code我希望正则表达式将 678954 视为长度为 6 的单个 integer 而不是长度为 3 的两个人。这样做的正确方法是什么,它应该替换以下代码

for num in re.findall("\d+","abc42h456k678954hars234ok001"):
    if len(num) == 3:
       li.append(num)

You can use (?:\D|^)(\d{3})(?:\D|$) to specify the preceding and following character for the pattern to be either non digit character or start / end of string:您可以使用(?:\D|^)(\d{3})(?:\D|$)将模式的前后字符指定为非数字字符或字符串的开头/结尾:

li = re.findall("(?:\D|^)(\d{3})(?:\D|$)","abc42h456k678954hars234ok001")

li    
# ['456', '234', '001']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM