regexp_replace替换了字符串的错误部分

时间:2014-09-09 16:52:11

标签: 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+导致匹配直到字符串结尾?

1 个答案:

答案 0 :(得分:1)

原因是(per documentation)

  

分支 - 也就是说,没有顶级的RE运营商 - 拥有   与其中具有贪婪属性的第一个量化原子相同的贪婪

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

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

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

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

并且不需要逃避冒号(:)。

SQL Fiddle.