用正則表達式【regexp】進行高級搜索數據


正則表達式介紹

正則表達式是用來匹配文本的特殊字符集合,如果你想從一個文本中提取電話號碼而已使用正則表達式,如果你需要查找名字中包含數字的所有文件可以使用正則,如果你你要在文本塊中找到所有重復的單詞,可以使用正則。

可以把正則【regexp】,直接理解為【去匹配】

基本字符匹配

我們用來檢索列prod_name包含文本luzhaosahn的所有行

select prod_name
from products
where prod_name regexp 'luzhaoshan'
order by prod_name;


查詢結果是:
prod_name
jetback    luzhaoshan

為什么要費力的使用正則表達式呢?因為在高級查詢中用處大大的好
例如:

select prod_name
from products
where prod_name regexp '.000'
order by prod_name;

輸出結果為:
prod_name

jetbaas    2000
hsahgj     8000
jaas    2000
ahgj     8000
jaas    2000
ahgj     8000

這里使用了正則表達式.000,是正則表達式語言中一個特殊的字符。它表示匹配任意一個字符,因此,2000和8000都匹配並且返回數據。
----當然這個也是可以使用like和通配符進行來完成的,如下參考:
select prod_name
from products
where prod_name like '%000'
order by prod_name;


對比來看:
select prod_name
from products
where prod_name regexp '.000'
order by prod_name;


----regexp 在列值內進行匹配
----like 匹配的是整個列
下面讓你們看一個神奇的地方!!!!!!!!!!!!
select prod_name
from products
where prod_name like '000'
order by prod_name;


對比來看:
select prod_name
from products
where prod_name regexp '.000'
order by prod_name;

#### 如果執行上述兩條語句,會發現第一條是不返回數據,而第二條語句返回一行,為什么??
因為,LIKE匹配整個列,如果被匹配的文本在列值內部中,並非是單獨的列,LIKE 將不會找到它,相應的行也不會返回,【除非使用通配符獲取數據】。


而REGEXP正好是在列值內部進行匹配,如果被匹配的文本在裂殖內部中,REGEXP就會找到它,相應的行也會返回。【這是一個非常重要的差別!!!】

REGEXP如果想要實現LIKE的功能,需要和^和$符合結合使用。

進行OR匹配,在正則表達式中使用 | 來表示OR的操作


select prod_name 
from products
where prod_name REGEXP  '1000|2000'
order by prod_name;

輸出結果為:
prod_name

jetpack    1000
jetmaoc    2000

語句中使用正則表達式1000|2000。 | 為正則表達式的or操作符。它表示匹配其中之一。因此1000和2000都匹配並且返回。

使用 | 從功能上類似於select語句中使用的or語句,多個or條件可以並入單個正則表達式。

----兩個以上的OR條件, 可以給出兩個以上的OR條件。例如,
‘1000 | 2000 | 3000’ 將匹配1000或者2000或者3000。

匹配指定字符,通過【】字符來完成

例如:


select prod_name
from products
where prod_name regexp '[123]ton'
order by prod_name;

輸出結果是:
prod_name
1 ton 
2 ton

這里使用正則表達式[123]ton,[123]定義一組字符,它的意思是匹配1 或者匹配2 或者匹配3,因此 1ton 和 2 ton 都匹配並且返回數據,(沒有3ton)

由此可知,[]是另一種形式的OR語句,事實上,正則表達式[123]ton為[1|2|3]ton
的縮寫,也可以使用后者。結果都是一樣的如下所示:
select prod_name
from products
where prod_name regexp '[1|2|3]ton'
order by prod_name;

輸出結果是:
prod_name
1 ton 
2 ton


[0-9]匹配任意0-9的字符
[a-z]匹配任意a-z的任意字母
例子如下:
select prod_name
from products
where prod_name regexp '[1-5]ton'
order by prod_name;

輸出結果為:
prod_name

1 ton anvil
2 ton anvil
3 ton anvil
.5 ton snkil

這里使用正則表達式[1-5]ton。定義了一個范圍,這個表達式意思是匹配到1-5,因此返回3個匹配行。 由於 5 ton 匹配,所以返回    .5ton

如果你想找出一個數或者以小數點開始的數,開始的所有產品,怎么辦,簡單搜索[0-9\.]不行的,因為它在文本中任意位置查找匹配,解決辦法就是使用^定位符。


^     文本的開始
$     文本的結束

select prod_name
from products
where prod_name regexp '^[0-9]\\.'
order by  prod_name

輸出結果為:
prod_name

1 ton anvil
2 ton anvil
3 ton anvil
.5 ton snkil

^ 匹配串的開始。
^的雙重用途,
第一個是在集合中用來否定該集合。
第二個是用來指示串的開始處。


簡單的正則表達式測試:
可以在不適用數據庫表的情況下用select來測試正則表達式,regexp檢查總是返回0
0是沒有匹配,1是匹配,可以使用帶文本串的regexp來測試表達式,並實驗他們
相應的測試如下:
select ‘hello’ regexp  ‘[0-9]’;
這個例子顯然將返回結果0,因為文本hello中沒有數字。




免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM