2010-01-11 26 views
3

我正在努力學習Oracle中的正則表達式(相當於我第一次嘗試使用RegEx進行任何操作)。關於Oracle中正則表達式的查詢

^是什麼意思在開頭? 說明文檔中提到

Use the caret and dollar sign to define patterns that match the start or end of a string. 
^ defines that start of a string or column 1 of the string. 

因此,通過使用'^[*est]'爲圖案,我的理解是,match anything which has -est as its ending

然而,當我嘗試過了,

SQL> select 1 from dual where regexp_like('test','^[*est]'); 

     1 
---------- 
     1 

SQL> select 1 from dual where regexp_like('best','^[*est]'); 

no rows selected 

SQL> select 1 from dual where regexp_like('fest','^[*est]'); 

no rows selected 

卸下^然而,我們得到

SQL> select 1 from dual where regexp_like('fest','[*est]'); 

     1 
---------- 
     1 

SQL> select 1 from dual where regexp_like('best','[*est]'); 

     1 
---------- 
     1 

SQL> select 1 from dual where regexp_like('test','^[*est]'); 

     1 
---------- 
     1 

爲什麼會這樣呢?爲什麼在第一種情況下,匹配發生在「測試」而不是其他人?

+1

很好的參考:http://www.regular-expressions.info/ – 2010-01-11 16:42:25

+0

@OMG小馬 - 感謝您的鏈接。 – Sathya 2010-01-12 12:26:50

回答

5
select 1 from dual where regexp_like('best','^[*est]'); 

[]在正則表達式的意思是「列出的任何字符」

[],星號失去了它的特殊含義,意思正好星號。

的正則表達式上述匹配開頭的任何字符串*est(任何以下的字符串的開始列出的字符)。

要選擇詞語上-est結束,使用:

select 1 from dual where regexp_like('nest','est$') 

這意味着「後面的字符串的結束的字符串est$)」

+0

所以我認爲它是第一個查詢的意思,匹配以'e','s','t','*'開始的任何字符串,而第二個查詢意味着匹配任何具有'e','s'的字符串, 't','*'? – Sathya 2010-01-12 12:26:04

+0

第二個查詢將匹配以'est'結尾的任何字符串(按該順序)。它會匹配'nest'和'best',但不匹配'nets'或'bets'。 – Quassnoi 2010-01-12 12:35:32

+0

爲了清楚起見,通過第二個查詢,我的意思是'regexp_like('fest','[* est]')' - 你說'[]'在regexps中的意思是「任何列出的字符」 - 所以我想確認這意味着匹配任何具有'e','s','t','*'的字符串。 對不起,如果我造成任何混淆 – Sathya 2010-01-12 13:34:32

2

除非Oracle中的正則表達式語法是非常不同的從所有其他正則表達式實現,然後你porbably想要將您的[]更改爲()[est]匹配「e」,「s」或「t」。另一方面,(est)與「est」匹配。