正則表達式是一種強大的字符串匹配工具,在Python中使用re模塊實現正則表達式操作。
一、match對象
在使用re模塊進行正則匹配時,會返回一個match對象。match對象包含匹配結果的信息,可以通過該對象獲取匹配結果。
import re
# 匹配字符串中的數字
pattern = r'\d+'
string = '12abc34def'
result = re.match(pattern, string)
if result:
# 獲取匹配內容
print(result.group())
# 獲取匹配的起始和結束位置
print(result.start(), result.end())
# 獲取匹配位置的元組
print(result.span())
運行結果:
12
0 2
(0, 2)
上述代碼中,使用match函數對字符串進行匹配,返回一個match對象result。使用group()方法獲取匹配內容,使用start()和end()方法獲取匹配的起始和結束位置,使用span()方法獲取匹配位置的元組。
二、group()方法
group()方法用於獲取匹配到的字符串。
import re
# 匹配字符串中的數字
pattern = r'\d+'
string = '12abc34def'
result = re.match(pattern, string)
if result:
print(result.group())
運行結果:
12
三、start()和end()方法
start()和end()方法用於獲取匹配的起始和結束位置。
import re
# 匹配字符串中的數字
pattern = r'\d+'
string = '12abc34def'
result = re.match(pattern, string)
if result:
print(result.start())
print(result.end())
運行結果:
0
2
四、span()方法
span()方法用於獲取匹配位置的元組(起始位置和結束位置)。
import re
# 匹配字符串中的數字
pattern = r'\d+'
string = '12abc34def'
result = re.match(pattern, string)
if result:
print(result.span())
運行結果:
(0, 2)
五、使用group()方法獲取分組匹配的結果
正則表達式中使用小括號括起來的部分稱為分組。可以使用group()方法獲取分組匹配的結果。
import re
# 匹配手機號碼
pattern = r'(\d{3})-(\d{8})'
string = '010-12345678'
result = re.match(pattern, string)
if result:
# 獲取完整匹配結果
print(result.group())
# 獲取分組匹配結果
print(result.group(1))
print(result.group(2))
運行結果:
010-12345678
010
12345678
六、使用span()方法獲取分組匹配的位置
使用span()方法獲取分組匹配的位置。
import re
# 匹配手機號碼
pattern = r'(\d{3})-(\d{8})'
string = '010-12345678'
result = re.match(pattern, string)
if result:
# 獲取完整匹配位置元組
print(result.span())
# 獲取分組匹配位置元組
print(result.span(1))
print(result.span(2))
運行結果:
(0, 12)
(0, 3)
(4, 12)
七、總結
re模塊返回的match對象是正則表達式匹配結果的對象,包含匹配結果的信息。可以使用group()、start()、end()和span()等方法獲取匹配結果的內容和位置信息。
在正則表達式中使用小括號括起來的部分稱為分組,可以使用group()和span()方法獲取分組匹配的結果和位置。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/194863.html