You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

正则表达式提取地址求助:从首个数字提取至末尾5位数字

问题:提取地址中的5位数字序列

需要从给定字符串里提取5位连续数字,但现有Python正则代码无法匹配到结果,不知道怎么写正确的规则。

原字符串:

"['Today is the open house of 1234 High Drive, Denver, COLORADO 80204; open to the Public "

错误代码:

import re

string = "['Today is the open house of 1234 High Drive, Denver, COLORADO 80204; open to the Public "

property_address = re.findall('\\d-\\d\\d\\d\\d\\d', str(string))

print(property_address)
解决方法

你的正则表达式\d-\d\d\d\d\d是在找“单个数字+减号+5个数字”的格式,但目标字符串里根本没有减号,所以匹配不到任何内容。

要提取连续的5位数字,直接用\d{5}这个正则规则就行,它表示匹配连续5个数字字符。

修正后的代码:

import re

string = "['Today is the open house of 1234 High Drive, Denver, COLORADO 80204; open to the Public "

# 匹配所有5位连续数字
property_address = re.findall(r'\d{5}', string)

print(property_address)  # 输出: ['80204']

如果你的需求是从字符串中第一个数字开始的内容里提取5位数字,可以先截取从第一个数字到末尾的子串,再匹配:

import re

string = "['Today is the open house of 1234 High Drive, Denver, COLORADO 80204; open to the Public "

# 定位第一个数字的位置
match = re.search(r'\d', string)
if match:
    sub_str = string[match.start():]
    property_address = re.findall(r'\d{5}', sub_str)
    print(property_address)  # 输出: ['80204']
else:
    print("没有找到数字")

内容的提问来源于stack exchange,提问作者Josh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 21:12:40