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

如何使用Regex将多个单词匹配为单个条目以提取商品名称?

解决方案

你的需求本质是提取每个列表项中第一个左括号前的内容,去除首尾空格即可,正则匹配逻辑如下:

  • 用^[^(]+匹配字符串开头到第一个(的全部内容
  • 对匹配结果调用.strip()去除首尾多余空白

可用代码示例

import re

# 编译正则模式
name_pattern = re.compile(r'^[^(]+')
# 你的原始商品列表
product_list = ['Milk (regular) (1 gallon)', 'Loaf of Fresh White Bread (1 lb)', 'Rice (white) (1 lb)', 'Eggs (regular) (12)', 'Local Cheese (1 lb)']

# 遍历提取商品名
extracted_names = [name_pattern.search(item).group().strip() for item in product_list]
print(extracted_names)

运行输出

['Milk', 'Loaf of Fresh White Bread', 'Rice', 'Eggs', 'Local Cheese']

原正则问题说明

你之前使用的r'[a-zA-Z]+\s'规则是匹配单个连续英文字母加空格的片段,所以会把完整商品名拆成单个单词的条目,不符合需求。


内容的提问来源于stack exchange,提问作者Alperen Açıkol

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 04:06:03