regexp_replace 替换字符串的错误部分

标签 regex postgresql pattern-matching postgresql-9.2

运行时:

select regexp_replace('( (test :Name (x) :Table (y) )','\s+\:Name \(.*?\)',' avner ');

我得到:

"( (test avner "

但是如果我运行:

select regexp_replace('( (test :Name (x) :Table (y) )','\:Name \(.*?\)',' avner ');

我得到:

"( (test  avner  :Table (y) )"

为什么开头的\s+会匹配到字符串的结尾?

最佳答案

原因是(per documentation) :

A branch — that is, an RE that has no top-level | operator — has the same greediness as the first quantified atom in it that has a greediness attribute.

大胆强调我的。将您的问题简化为:

SELECT substring('( (test :Name (x) :Table (y) )', '\s+\:Name \(.*?\)')
      ,substring('( (test :Name (x) :Table (y) )',    '\:Name \(.*?\)')

如果您希望第二个量词是非贪婪的,请将第一个量词也更改为非贪婪。特别是,因为这不会改变任何东西:

SELECT substring('( (test :Name (x) :Table (y) )', '\s+<b>?</b>:Name \(.*?\)')

而且不需要转义冒号(:)。

SQL Fiddle.

关于regexp_replace 替换字符串的错误部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25750062/

相关文章:

python - 使用正则表达式增加版本号

java - 单括号java正则表达式

仅限制记录子集的 SQL 查询

java - java中的重复正则表达式模式

F# 与复杂类型匹配

regex - 正则表达式用于获取最后一个斜杠之后的所有内容

java - Java 中的正则表达式仅匹配 .css 方法签名中出现的逗号

postgresql - 在 plpgsql 中插入时使用 quote_literal

sql - 查询值为空的单行的列名?

syntax - 一元计算中的短路 "uninteresting"情况