2012-07-19 73 views
1

这些话来允许括号在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 
+0

1'jaffrei'字损害你的正则表达式 2.我不明白 - 你想提取它之前的数字或文字? '计数器'表示第一个,'[1]'表示第二个。 – LisMorski 2012-07-19 12:11:45

+0

这个问题目前还不清楚。请添加一个字符串示例以及您想要从中获得的内容。 – 2012-07-19 13:05:09

回答

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 

简化的regexp,松无意义字符类:

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]+'); 
+0

好的,感谢您的回答,我发现没有机会避免在最终选择语句之前以某种方式编辑文本(在\添加\或\)之前(实际上我给出的示例只是更复杂的一部分句子)。我期望正则表达式中的某些选项可以避免......谢谢 – user1249791 2012-07-19 14:45:15