1. 程式人生 > >re模組操作

re模組操作

在Python中需要通過正則表示式對字串進行匹配的時候,可以使用一個模組,名字為re

1. re模組的使用過程

#coding=utf-8

# 匯入re模組
import re

# 使用match方法進行匹配操作
result = re.match(正則表示式,要匹配的字串)

# 如果上一步匹配到資料的話,可以使用group方法來提取資料
result.group()

re.match是用來進行正則匹配檢查的方法,若字串匹配正則表示式,則match方法返回匹配物件(Match Object),否則
返回None(注意不是空字串"")。

匹配物件Macth Object具有group方法,用來返回字串的匹配部分。

2. re模組示例(匹配以rongexue開頭的語句)

#coding=utf-8
import re
result = re.match("rongexue","rongexue.cn")
result.group()

執行結果為:

rongexue

3. 說明

re.match() 能夠匹配出以xxx開頭的字串