1. 程式人生 > >(五)5-3Python正則表達式

(五)5-3Python正則表達式

sta repr log 直接 mat 轉換成 and das 配對

正則對象的方法

1、match 方法

import  re
reg = re.compile(r(hello w.*)(hello cn.*))
a = hello world hello cnblogs
result = reg.match(a)
print(result)

b = "aa" + a
print(b)
result2 = reg.match(b)
print(result2)

運行結果:

<_sre.SRE_Match object at 0x00000000025E21C8>
hello world hello cnblogs
aahello world hello cnblogs
None

2、search方法

import  re
reg = re.compile(r(hello w.*)(hello cn.*))
a = hello world hello cnblogs
b = "aa" + a
print(b)
result3 = reg.search(b)
print(result3)
print(result3.group())

運行結果:

aahello world hello cnblogs
<_sre.SRE_Match object at 0x0000000002592140>
hello world hello cnblogs

3、正則對象的split方法

import re
p = re.compile(r\d+)
print(p.split(one1two2three3four4))

運行結果:

[one, two, three, four, ‘‘]

註:直接把p的正則當成分隔符,然後把最後的字符串用p進行分割,最終返回結果

4、正則對象的findall方法
findall(string[,pos[,endpos]])
搜索string,以列表形式返回全部能匹配的字符串

import re
p = re.compile(r\d+)
print(p.findall(one1two2three3four4))

運行結果

[1, 2, 3, 4]

註:findall把匹配的字符串最後一列表的形式返回

5、正則對象的finditer方法
finditer(string[,pos[,endpos]])
搜索string,返回一個順序訪問每一個結果(match對象)的叠代器
import re
p = re.compile(r\d+)
a_string = one1two2three3four4
for i in p.finditer(a_string):
    # print(i)
    print(type(i))
    print(i.group())

運行結果:

<type _sre.SRE_Match>
1
<type _sre.SRE_Match>
2
<type _sre.SRE_Match>
3
<type _sre.SRE_Match>
4

註:p.finditer(a_string)是一個叠代器,返回的每個m都是match對象

6、正則對象的sub方法

sub(pattern, repl, string, count=0)
pattern : 正則中的模式字符串。
repl : 替換的字符串,也可為一個函數。
string : 要被查找替換的原始字符串。
count : 模式匹配後替換的最大次數,默認 0 表示替換所有的匹配。

match匹配對象

import  re
reg = re.compile(r(?P<tagname>abc)(.*)(?P=tagname))
result = reg.match(abclfjasdasda234hhkhabc)

print(dir(result))
print(result)
print(result.groups())
print(result.group(2))
print(result.group(tagname))
print(**10)
print(result.groupdict())

運行結果:

[__class__, __copy__, __deepcopy__, __delattr__, __doc__, __format__, __getattribute__, __hash__, __init__, __new__, __reduce__, __reduce_ex__, __repr__, __setattr__, __sizeof__, __str__, __subclasshook__, end, endpos, expand, group, groupdict, groups, lastgroup, lastindex, pos, re, regs, span, start, string]
<_sre.SRE_Match object at 0x0000000002662140>
(abc, lfjasdasda234hhkh)
lfjasdasda234hhkh
abc
**********
{tagname: abc}

註:
1、 result 由字符串轉換成了正則對象
2、 result.groups()是所有的匹配到的數據,每個()是一個元素,最終返回一個tuple
3、 group()可以通過下標(從1開始)的方式訪問,也可以通過分組名進行訪問
4、 groupdict只能顯示有分組名的數據

(五)5-3Python正則表達式