运行时:
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 \(.*?\)')
而且不需要转义冒号(:
)。
关于regexp_replace 替换字符串的错误部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25750062/