Google Sheets正则替换URL双连字符问题求助
解决Google Sheets生成SEO URL关键词时的双连字符问题
我在Google表格中制作工具生成公司产品的SEO友好URL关键词,目标格式为gold-blue-glass-ornament-collection-set-of-3。当前使用的公式:LOWER(REGEXREPLACE(SUBSTITUTE(C2, " ", "-"),"[\&(\)/']",""))
能完成空格替换、过滤&、括号、撇号等特殊字符,但处理含&的标题(如Gold & Blue Glass Ornament Collection (Set of 3))时,会输出带双连字符的结果gold--blue-glass-ornament-collection-set-of-3,需要修正为单连格式。
输入输出示例
| 输入 | 当前输出 | 期望输出 |
|---|---|---|
| Gold & Blue Glass Ornament Collection (Set of 3) | gold--blue-glass-ornament-collection-set-of-3 | gold-blue-glass-ornament-collection-set-of-3 |
| Poppies Glass Ornament Collection (Set of 3) | poppies-glass-ornament-collection-set-of-3 | poppies-glass-ornament-collection-set-of-3 |
| Calla Lilies Glass Ornament Collection (Set of 3) | calla-lilies-glass-ornament-collection-set-of-3 | calla-lilies-glass-ornament-collection-set-of-3 |
| The Flamingoes Glass Ornament Collection (Set of 3) | the-flamingoes-glass-ornament-collection-set-of-3 | the-flamingoes-glass-ornament-collection-set-of-3 |
| Japanese Bridge Glass Ornament Collection (Set of 3) | japanese-bridge-glass-ornament-collection-set-of-3 | japanese-bridge-glass-ornament-collection-set-of-3 |
| Van Gogh's Specialty Glass Ornament Collection (Set of 3) | van-goghs-glass-ornament-collection-set-of-3 | van-goghs-glass-ornament-collection-set-of-3 |
问题原因
原公式先将空格替换为-,再删除特殊字符。以Gold & Blue为例,会先变成Gold-&-Blue,删除&后就留下Gold--Blue,导致双连字符。
修正方案
调整处理顺序:先删除特殊字符,再将**连续的空格(包括删除特殊字符后产生的多空格)**替换为单个-,最后转小写。
修正后的公式:LOWER(REGEXREPLACE(REGEXREPLACE(C2, "[\&(\)/']", ""), "\s+", "-"))
公式解析
- 第一层
REGEXREPLACE(C2, "[\&(\)/']", ""):移除&、(、)、/、'这些指定特殊字符 - 第二层
REGEXREPLACE(..., "\s+", "-"):把一个或多个连续的空格统一替换为单个连字符-,避免多空格转成多连字符 LOWER(...):将最终字符串转为小写,符合SEO URL的小写规范
如果后续需要过滤更多特殊字符,只需在[\&(\)/']的字符集中添加对应的符号即可(比如要过滤!就改成[\&(\)/'!])。
内容的提问来源于stack exchange,提问作者dickinsonk9
相关产品推荐
相关产品推荐

