在postgreSQL正则表达式文本中允许括号

时间:2012-07-19 11:44:05

标签: sql regex postgresql

这些句子有效

SELECT (regexp_matches('Euroschinus Hoff+300'::text, E'(Euroschinus Hoff[\+])([0- 9]+)'::text)::text[])[1]::text as counter 
select array_scientificname from simple_cal where array_scientificname ~ 'Semecarpus'

但是,如果有一些括号,请不要介意文本中的哪些内容都不起作用

SELECT (regexp_matches('Euroschinus (testing) Hoff+300'::text, E'(Euroschinus (testing)  Hoff[\+])([0-9]+)'::text)::text[])[1]::text as counter 
select array_scientificname from simple_cal where array_scientificname ~  'Semecarpus(test)'

我只是想得到,文字。 ()没有定义的模式,可以在文本的任何位置。

我注意到在括号之前使用\它可以解决问题(见下文),但这根本不实用。我想我应该在字符串中包含允许()的地方...

SELECT (regexp_matches('Euroschinus (testing) Hoff+300'::text, E'(Euroschinus jaffrei \\(testing\\) Hoff[\+])([0-9]+)'::text)::text[])[1]::text as counter

1 个答案:

答案 0 :(得分:2)

这不会返回任何内容:

SELECT (regexp_matches(
         'Euroschinus (testing) Hoff+300'::text
     , E'(Euroschinus jaffrei \\(testing\\) Hoff[\\+])([0-9]+)')::text[])[1]::text;

从模式中删除字符串jaffrei之后会这样做:

SELECT (regexp_matches(
         'Euroschinus (testing) Hoff+300'::text
     , E'(Euroschinus \\(testing\\) Hoff[\\+])([0-9]+)')::text[]);[1]::text

简化正则表达式,松散无意义的字符类:

SELECT (regexp_matches(
         'Euroschinus (testing) Hoff+300'::text
     , E'(Euroschinus \\(testing\\) Hoff\\+)([0-9]+)')::text[])[1]::text;

如果您不得不添加反斜杠,请尝试设置standard_conforming_strings(默认自PostgreSQL 9.1)并使用普通字符串而不是Posix转义序列:

SELECT (regexp_matches(
         'Euroschinus (testing) Hoff+300'::text
     , '(Euroschinus \(testing\) Hoff\+)([0-9]+)')::text[])[1]::text;

但如果您只对第一次点击感兴趣,那么您最好先使用substring()。捕获括号选择你想要的字符串:

SELECT substring('Euroschinus (testing) Hoff+300'
              , '(Euroschinus \(testing\) Hoff\+)[0-9]+');

最后,如果您对字符串()中仅存在(??)感到困扰,请将其删除:

SELECT substring(translate('Euroschinus (testing) Hoff+300', '()', '')
                        , '(Euroschinus testing Hoff\+)[0-9]+');
相关问题