PostgreSQL正则表达式,不区分大小写

Pie*_*e D 3 regex postgresql case-insensitive

使用PostgreSQL v.8.2.14,我正在尝试构建一个包含多个分支的正则表达式,其中一些分支不区分大小写,其他分支则不大.

考虑以下perl one-liner:

% echo 'foo Foo bar Bar' | perl -pe 's/(foo|(?i:bar))/_\1/g'
_foo Foo _bar _Bar
Run Code Online (Sandbox Code Playgroud)

我以为我会到达那里:

select regexp_replace('foo Foo bar Bar','(foo|((?i)bar)',E'_\\1','g');
Run Code Online (Sandbox Code Playgroud)

但我明白了:ERROR: invalid regular expression: quantifier operand invalid.注意regex_flavor是高级的,当我把(?i)放在regexp的最开头时BTW,然后没有错误:

select regexp_replace('foo Foo bar Bar','(?i)(foo|bar)',E'_\\1','g');
 _foo _Foo _bar _Bar
Run Code Online (Sandbox Code Playgroud)

任何帮助都很高兴.

mu *_*ort 5

(?i)(和相关的选项)仅在表达式的开头有效.从精细手册:

ARE可以嵌入选项开始:序列(?xyz)(其中xyz是一个或多个字母字符)[...]

强调我的.该(?xyz)选项类似于尾随/.../xyz其他语言的正则表达式选项.另请注意,9.0手册使用相同的语言,因此您不能只是升级方式.

看起来你需要两个regexp_replace电话:

> select regexp_replace(regexp_replace('foo Foo bar Bar', 'foo', E'_\\&', 'g'), 'bar',  E'_\\&', 'ig');
   regexp_replace   
--------------------
 _foo Foo _bar _Bar
Run Code Online (Sandbox Code Playgroud)

或者不区分大小写匹配困难的方式(即字符类):

> select regexp_replace('foo Foo bar Bar', '(foo|[Bb][Aa][Rr])', E'_\\1', 'g');
   regexp_replace   
--------------------
 _foo Foo _bar _Bar
Run Code Online (Sandbox Code Playgroud)