python進階18正則表達式

原創博客鏈接:python進階18正則表達式

正則基礎知識

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
^`:匹配行首
`$`:匹配結尾
`*`:(**貪婪**)前面字符匹配任意多次
`+`:(**懶惰**)前面字符匹配1或者更多次
`?`:前面字符匹配0或1次,還作爲懶惰限定符使用,詳看後面

`{m}`:前面字符匹配m次
`{m,n}`:前面字符匹配m~n次
`{m,}`:前面字符匹配m或更多次
`{,n}`:前面字符匹配0~n次

`|`:或,必須加括號

`.`:匹配除換行符以外的任意字符
`[1357]`:匹配1,3,5,7中其中一個數字,當然也可以是字母
`[0-9]`:匹配0到9的其中一個數字,類似用法還有:[a-zA-Z]
`[\u4E00-\u9FA5]`:匹配中文
`[^012]`:表示除012外的任意字符,包括3-9,a-z,A-Z,等等
注意:[]裏面的.和*等一些特殊字符都失去特殊意義,只表示本身。

分組捕獲

 

1
2
3
4
5
6
7
8
9
10
11
import re
str = 'booy123'
regex = '((boy|booy)123)'

# 如果有多個括號,則從最外面往裏算,從1開始

re_match = re.match(regex, str)
re_match.group(1)
# 'booy123'
re_match.group(2)
# 'booy'

懶惰限定符

如果有多個貪婪,則第一個最貪婪

 

1
2
3
4
5
6
7
*? :重複任意次,但儘可能少重複
+? :重複1次或更多次,但儘可能少重複
?? :重複0次或1次,但儘可能少重複
{n,m}? :重複n到m次,但儘可能少重複
{n,}?: 重複n次以上,但儘可能少重複
str = 'abooabbapds aboksldap'
obj = re.compile('ab.*?ap') #注意用非貪婪匹配,不然list裏只有一個

匹配和搜索

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
match_list = obj.findall(str)  #match_list是一個list
# match_list -> ['abooabbap','aboksldap']

for match in match_list:
    print(match)
# 輸出
# abooabbap
# aboksldap
import re

str = 'abooabbapds aboksldap'
obj = re.compile('ab.*?ap')
match_list = obj.finditer(str)
# match_list -> callable_iterator對象,需要用group()查詢

for match in match_list:
    print(match.group())
# abooabbap
# aboksldap

參考

Python正則表達式急速入門:https://baijiahao.baidu.com/s?id=1652504385879645545&wfr=spider&for=pc
正則表達式必知必會:python.iswbm.com/en/latest/c01/c01_11.html
Python 正則表達式:https://www.runoob.com/python/python-reg-expressions.html
Python正則表達式指南:https://www.cnblogs.com/huxi/archive/2010/07/04/1771073.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章