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

如何编写正则表达式仅匹配以1开头的特定格式产品ID?

解决方案

要让正则仅匹配以1开头的产品ID,只需修改原正则的开头规则,将任意四位数字(\d{4})替换为以1开头的四位数字,同时增加单词边界避免误匹配长字符串的片段。

修正后的正则模式为:

r'\b1\d{3}-[A-Z]{2}-\d{2}\b'

模式细节说明:

  • \b:单词边界,确保匹配的是独立完整的产品ID,不会从更长的字符串(如12345-AB-30)中截取无效片段
  • 1:强制产品ID的四位数字部分以1开头
  • \d{3}:匹配后续三位任意数字,凑齐开头的四位数字
  • -:匹配固定的连字符分隔符
  • [A-Z]{2}:匹配两位大写字母(和原逻辑一致,也可写成[A-Z][A-Z])
  • -\d{2}:匹配末尾的连字符加两位数字

修改后的完整代码:

import re

def find_productID(report):
  pattern = r'\b1\d{3}-[A-Z]{2}-\d{2}\b'
  result = re.findall(pattern, report)
  return result

print(find_productID("Products 1234-AB-30 and 2234-AB-30, not items 12-AB-30 or 12345-AB-30")) # 返回 ['1234-AB-30']
print(find_productID("Products of interest are 1234-AB-30, 1678-XZ-11, and 1561-CD-57. We're not interested in other products like 2345-AB-29.")) # 返回 ['1234-AB-30', '1678-XZ-11', '1561-CD-57']

运行代码后,输出结果完全符合预期需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 09:00:19