01、正則表達式相關
阿新 • • 發佈:2017-10-12
obj pytho idt 可能 電話 clas line proc log
一、常見的正則表達式匹配模式
代碼 | 說明 |
---|---|
. | 匹配除換行符以外的任意字符 |
\w | 匹配字母或數字或下劃線或漢字 |
\s | 匹配任意的空白符 |
\d | 匹配數字 |
\b | 匹配單詞的開始或結束 |
^ | 匹配字符串的開始 |
$ | 匹配字符串的結束 |
代碼/語法 | 說明 |
---|---|
* | 重復零次或更多次 |
+ | 重復一次或更多次 |
? | 重復零次或一次 |
{n} | 重復n次 |
{n,} | 重復n次或更多次 |
{n,m} | 重復n到m次 |
代碼/語法 | 說明 |
---|---|
\W | 匹配任意不是字母,數字,下劃線,漢字的字符 |
\S | 匹配任意不是空白符的字符 |
\D | 匹配任意非數字的字符 |
\B | 匹配不是單詞開頭或結束的位置 |
[^x] | 匹配除了x以外的任意字符 |
[^aeiou] | 匹配除了aeiou這幾個字母以外的任意字符 |
代碼/語法 | 說明 |
---|---|
*? | 重復任意次,但盡可能少重復 |
+? | 重復1次或更多次,但盡可能少重復 |
?? | 重復0次或1次,但盡可能少重復 |
{n,m}? | 重復n到m次,但盡可能少重復 |
{n,}? | 重復n次以上,但盡可能少重復 |
二、正則表達式的實際使用
實例1:.*?的使用詳情
import re line = ‘booooooobbbbbby123‘ regex_str= ‘.*?(b.*?b).*‘ match_obj = re.match(regex_str,line) if match_obj: print(match_obj.group(1))
運行結果:
C:\Users\licl11092\AppData\Local\Programs\Python\Python35\python.exe D:/Scrapy/test/test.py booooooob Process finished with exit code 0
實例2:|和()的使用
import re line = ‘boobby123‘ regex_str = ‘((bobby|boobby)123)‘ match_obj = re.match(regex_str,line) if match_obj: print(match_obj.group(1)) print(match_obj.group(2))
運行結果:
C:\Users\licl11092\AppData\Local\Programs\Python\Python35\python.exe D:/Scrapy/test/test.py boobby123 boobby Process finished with exit code 0
實例3:提取電話號碼([]的使用)
import re line = ‘15868197032fsfs‘ regex_str = ‘(1[34578][0-9]{9})‘ match_obj = re.match(regex_str,line) if match_obj: print(match_obj.group(1))
運行結果:
C:\Users\licl11092\AppData\Local\Programs\Python\Python35\python.exe D:/Scrapy/test/test.py 15868197032 Process finished with exit code 0
實例4:\s的使用舉例
import re line = ‘你 好‘ regex_str = ‘(你\s好)‘ match_obj = re.match(regex_str,line) if match_obj: print(match_obj.group(1))
運行結果:
C:\Users\licl11092\AppData\Local\Programs\Python\Python35\python.exe D:/Scrapy/test/test.py 你 好 Process finished with exit code 0
實例5:[\u4e00-\u9fa5] 的使用舉例
import re line = ‘你好‘ regex_str = ‘([\u4e00-\u9fa5]+)‘ match_obj = re.match(regex_str,line) if match_obj: print(match_obj.group(1))
運行結果:
C:\Users\licl11092\AppData\Local\Programs\Python\Python35\python.exe D:/Scrapy/test/test.py 你好 Process finished with exit code 0
實例6:舉例說明提取多種書寫方式的出生年月日
import re line = ‘xxx出生於2001年6月‘ line2 = ‘xxx出生於2001/6/1‘ line3 = ‘xxx出生於2001-6-1‘ line4 = ‘xxx出生於2001-06-01‘ line5 = ‘xxx出生於2001-06‘ regex_str = ‘.*出生於(\d{4}[年/-]\d{1,2}($|[月/-]$|[月/-]\d{1,2}))‘ match_obj = re.match(regex_str,line) match_obj2 = re.match(regex_str,line2) match_obj3 = re.match(regex_str,line3) match_obj4 = re.match(regex_str,line4) match_obj5 = re.match(regex_str,line5) if match_obj: print(match_obj.group(1)) print(match_obj2.group(1)) print(match_obj3.group(1)) print(match_obj4.group(1)) print(match_obj5.group(1))
運行結果:
C:\Users\licl11092\AppData\Local\Programs\Python\Python35\python.exe D:/Scrapy/test/test.py 2001年6月 2001/6/1 2001-6-1 2001-06-01 2001-06 Process finished with exit code 0
01、正則表達式相關