PostgreSQL 12正则表达式修改:提取符合规则的产品名称前缀
问题场景
现有产品名称样本:
Product one white Adidas Other product black Hill sheet Nice T-shirt blue Brower company
需要提取从开头到第一个大写起始单词(排除"T-shirt")之前的全部内容,预期输出如下:
Product one white Other product black Nice T-shirt blue
之前使用的正则表达式:
regexp_replace('Nice T-shirt blue Brower company', '(?<!^)\m[A-ZÕÄÖÜŠŽ].*', '')
在处理Nice T-shirt blue Brower company时返回了Nice,不符合需求,需修改正则适配PostgreSQL 12环境。
修正方案
使用以下正则表达式可得到正确结果:
regexp_replace(your_column_name, '^(.*?)\m(?!T-shirt)[A-ZÕÄÖÜŠŽ].*', '\1')
正则说明
\m:PostgreSQL中的单词起始锚点,用于定位单词开头(?!T-shirt):负向前瞻断言,跳过恰好是"T-shirt"的单词,避免误截断[A-ZÕÄÖÜŠŽ]:匹配所有大写起始的单词(包含指定的特殊大写字符)^(.*?):非贪婪捕获从文本开头到目标单词之前的所有内容,替换时用\1保留该捕获内容,直接截断后续部分
测试验证
将修正后的正则应用到样本文本:
- 输入
Product one white Adidas→ 输出Product one white - 输入
Other product black Hill sheet→ 输出Other product black - 输入
Nice T-shirt blue Brower company→ 输出Nice T-shirt blue
内容的提问来源于stack exchange,提问作者Andrus
相关产品推荐
相关产品推荐

