正則表達式常用匹配規則:
.匹配任意字符,但是不能匹配換行符
\d匹配任意數字
\D匹配任意的非數字
\s匹配的是空白字符(包括:\n,\t,\r和空格)
\w匹配的是a-z和A-Z以及數字和下划線
\W匹配的是和\w相反的
[]組合的方式,只要滿足中括號中的某一項都算匹配成功
之前講到的幾種匹配規則,其實可以使用中括號的形式來進行替代:
\d:[0-9]
\D:[^0-9]
\w:[0-9a-zA-Z_]
\W:[^0-9a-zA-Z_]
匹配多個字符:
*:可以匹配0或者任意多個字符
text = "0731" ret = re.match('\d*',text) print(ret.group()) >> 0731
+:可以匹配1個或者多個字符
text = "abc" ret = re.match('\w+',text) print(ret.group()) >> abc
?:匹配的字符可以出現一次或者不出現(0或者1)
text = "123" ret = re.match('\d?',text) print(ret.group()) >> 1
{m}:匹配m個字符
text = "123" ret = re.match('\d{2}',text) print(ret.group()) >> 12
{m,n}:匹配m-n個字符
text = "123" ret = re.match('\d{1,2}',text) prit(ret.group()) >> 12
^(脫字號):表示以...開始
text = "hello" ret = re.match('^h',text) print(ret.group()) 如果是在中括號中,那么代表的是取反操作.
$:表示以...結束
# 匹配163.com的郵箱
text = "xxx@163.com" ret = re.search('\w+@163\.com$',text) print(ret.group()) >> xxx@163.com
|:匹配多個表達式或者字符串
text = "hello world." ret = re.findall('hello|\s',text) print(ret) >> ['hello', ' ']
貪婪模式:正則表達式會匹配盡量多的字符。默認是貪婪模式。
非貪婪模式:正則表達式會盡量少的匹配字符。
關於轉義
這里會涉及兩方面轉義,第一是python解釋器的轉義,第二是正則的轉義
比如一個str = "asd\nd" 要匹配出其中的\n,使用search("\n",str)首先\n會被python解釋器理解為換行,要解決這個問題我們可以用search(r"\n",str)表示使用原生字符
第二是正則里會把\n識別為換行符,要解決這個問題我們可以用search(r"\\n",str) ,\\n表示對元字符\n轉義表達原生字符"\n"
re模塊中常用函數:
match:從開始的位置進行匹配。如果開始的位置沒有匹配到。就直接失敗了。
text = 'hello' ret = re.match('h',text) print(ret.group()) >> h
search:
在字符串中找滿足條件的字符。如果找到,就返回。說白了,就是只會找到第一個滿足條件的。
text = 'apple price $99 orange price $88' ret = re.search('\d+',text) print(ret.group()) >> 99
group 分組:
在正則表達式中,可以對過濾到的字符串進行分組。分組使用圓括號的方式。
group
:和group(0)
是等價的,返回的是整個滿足條件的字符串。groups
:返回的是里面的子組。索引從1開始。group(1)
:返回的是第一個子組,可以傳入多個。
text = "apple price is $99,orange price is $10" ret = re.search(r".*(\$\d+).*(\$\d+)",text) print(ret.group()) print(ret.group(0)) print(ret.group(1)) print(ret.group(2)) print(ret.groups())
findall:
找出所有滿足條件的,返回的是一個列表。
text = 'apple price $99 orange price $88' ret = re.findall('\d+',text) print(ret) >> ['99', '88']
sub:
用來替換字符串。將匹配到的字符串替換為其他字符串。
text = 'apple price $99 orange price $88' ret = re.sub('\d+','0',text) print(ret) >> apple price $0 orange price $0
split:
使用正則表達式來分割字符串。
text = "hello world ni hao" ret = re.split('\W',text) print(ret) >> ["hello","world","ni","hao"]
compile:
對於一些經常要用到的正則表達式,可以使用compile進行編譯,后期再使用的時候可以直接拿過來用,執行效率會更快。
text = "the number is 20.50" r = re.compile(r""" \d+ # 小數點前面的數字 \.? # 小數點 \d* # 小數點后面的數字 """,re.VERBOSE) ret = re.search(r,text) print(ret.group())