SQL中使用regexp_replace移除句首单字符首词的实现方案
正则替换实现方案
直接用regexp_replace配合开头锚定的正则就能实现,全程不会改动字符串中间的空格、标点等内容,完全匹配你的需求。
核心写法
regexp_replace(location, '^. +', '')
正则逻辑说明
^:锚定字符串起始位置,保证规则只在字符串开头生效,绝对不会误改中间内容.:匹配任意单个字符,对应长度为1的首词/首字符+:匹配首字符后衔接的1个及以上连续空格- 如果开头首词长度大于1,第一个字符后会紧跟其他非空格字符,
+规则匹配失败,字符串会原样保留,不会做任何修改
相比split拆分再string_agg拼接的实现方式,这个写法不会破坏字符串中间的多空格、特殊符号格式,执行效率也更高。
完整运行示例
执行下面的SQL就能直接得到你期望的结果:
with t1 as ( select 1 id,"1 university of washington, seattle, washington" location union all select 2 id,"a university of washington, seattle , washington" union all select 3 id,"b university of washington, , washington" union all select 4 id,"university of washington, seattle , washington" union all select 5 id,"d university of new york,ny , usa" union all select 6 id,"university of new york,new york , usa" ) select id, regexp_replace(location, '^. +', '') as location from t1 order by 1
扩展兼容(可选)
如果你的数据里存在字符串开头带前导空格的情况(比如" xxxx"格式),需要先跳过前导空格再判断首词长度,可以把正则替换成下面的写法,会自动忽略开头的任意个前导空格再做匹配:
regexp_replace(location, '^ *[^ ] +', '')
内容的提问来源于stack exchange,提问作者Denis The Menace
相关产品推荐
相关产品推荐

