2012-07-19 29 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