仅当 street 后面没有任何字母时,我才尝试将 street 替换为 st。如果在 street 之后有非字母字符或字符串结尾,则允许替换。
我试图在 Postgresql 9.5 regex_replace 函数中实现这一点。我写的示例查询:
select regexp_replace('super streetcom','street(?!=[a-z])','st');
这里的street 不应该被st 取代,因为street 后面跟着'c'。所以预期的输出是“super streetcom”,但我得到的输出是“super stcom”。
对于为什么我得到意外输出以及什么是实现预期结果的正确方法有任何帮助。
最佳答案
一个lookahead construct看起来像(?!...)
,?!
后面的都是一个lookahead模式,引擎会尝试匹配,一旦找到,匹配就会失败.
看来您需要匹配整个单词street
。使用 \y
,单词边界:
select regexp_replace('super streetcom street','\ystreet\y','st');
请参阅online demo
来自 docs :
\y
matches only at the beginning or end of a word
关于regex - Postgresql regexp_replace 负向前瞻不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44845053/