Python正则如何匹配指定字符串及后续固定长度的任意字符?
需求实现说明
结论
该需求完全可以通过Python的正则功能实现,无需额外拆分字符串处理。
实现逻辑
利用正则的.通配符匹配任意字符,配合量词{n}指定匹配长度,直接匹配「固定前缀+后续指定长度字符」的规则即可。
具体代码实现
1. 固定截取长度写法(示例截取前缀后61个字符)
import re text = '''"number='/address/1234'>1234</separator></separator></separator><separator>some more data here</separator><separator>number='/address/5678901234'>5678901234</separator></separator></separator><separator>even more data on this spot</separator><separator>"''' # 正则模式:匹配固定前缀 + 后续61个任意字符 pattern = r"number='/address/.{61}" result = re.findall(pattern, text) print(result)
2. 动态指定截取长度写法
如果需要灵活调整后续截取长度,可使用f字符串动态生成正则规则:
import re def extract_prefix_with_suffix(text, suffix_len=61): # 注意f字符串中表示正则量词的{}需要双写转义 pattern = rf"number='/address/.{{{suffix_len}}}" # 如果文本包含换行符,需要加re.DOTALL参数让.匹配换行 # return re.findall(pattern, text, flags=re.DOTALL) return re.findall(pattern, text) # 调用示例 text = '''"number='/address/1234'>1234</separator></separator></separator><separator>some more data here</separator><separator>number='/address/5678901234'>5678901234</separator></separator></separator><separator>even more data on this spot</separator><separator>"''' print(extract_prefix_with_suffix(text, 61))
运行结果
和预期结果完全一致:
[ "number='/address/1234'>1234</separator></separator></separator><separator>some", "number='/address/5678901234'>5678901234</separator></separator></separator><se" ]
特殊场景兼容
如果存在前缀后剩余字符不足指定长度的场景,可将正则量词改为{1,61},此时剩余字符不足61个时也会返回能匹配到的最大长度内容,示例规则:
pattern = r"number='/address/.{1,61}"
内容的提问来源于stack exchange,提问作者Chipe
相关产品推荐
相关产品推荐

