正則表達式是一個特殊的字符序列,它能幫助你方便的檢查一個字符串是否與某種模式匹配。html
Python 1.5版本增長了re模塊,提供了Perl風格的正則表達模式。python
re模塊讓Python語言擁有所有的正則表達式功能。正則表達式
compile 函數根據一個模式字符串和可選的標誌參數生成一個正則表達式對象。該對象擁有一系列方法用於正則表達式匹配和替換。函數
re 模塊也提供了與這些方法功能徹底一致的函數,這些函數使用一個模式字符串作爲它們的第一個參數。post
re.match函數
re.match嘗試從字符串起始位置匹配一個模式,若是不是起始位置匹配成功的話,match()就返回none.url
函數語法:
1
|
re.match(pattern, string, flags
=
0
)
|
pattern 匹配正則表達式spa
string 要匹配的字符串code
flags 標誌位,用於控制正則表達式匹配方式,例如:是否區分大小寫,多行匹配等等。htm
匹配成功re.match方法返回一個匹配對象,不然返回None對象
咱們能夠使用group(num)或groups()匹配對象函數來獲取匹配表達式。
匹配對象方法 | 描述 |
group(num=0) | 匹配的整個表達式的字符串,group()能夠一次輸入多個組號,在這種狀況下它將返回一個包含那些組對應值的元組。 |
groups | 返回一個包含全部小組字符串的元組,從1到 所含的小組號 |
例子1
1
2
3
4
|
import
re
print
(re.match(
'www'
,
'www.siit.com'
).span())
#起始位置匹配
print
(re.match(
'com'
,
'www.siit.com'
))
#不在起始位置
|
輸出:
1
2
|
(
0
,
3
)
None
|
例子2
1
2
3
4
5
6
7
8
9
10
|
<br>
import
re
line
=
"who are your ? dog?"
matchObj
=
re.match(r
'(.*) are (.*?) .*'
, line, re.M|re.I)
if
matchObj:
print
(
"matchObj.group():"
,matchObj.group())
print
(
"matchObj.group(1):"
,matchObj.group(
1
))
print
(
"matchObj.group(2):"
,matchObj.group(
2
))
else
:
print
(
"No match!!"
)
|
輸出:
1
2
3
|
matchObj.group(): who are your ? dog?
matchObj.group(
1
): who
matchObj.group(
2
): your
|