python笔记-----正则表达式

创建正则表达式对象

import re

常用匹配语法

re.match 从头开始匹配

re.search 匹配包含

re.findall 把所有匹配到的字符放到以列表中的元素返回

re.splitall 以匹配到的字符当做列表分隔符

re.sub 匹配字符并替换

re.compile(r'(\d\d\d)-(\d\d\d-\d\d\d\d)')  创建匹配对象

常用正则表达式符号

. 默认匹配除\n之外的任意一个字符,若指定flag DOTALL,则匹配任意字符,包括换行

^ 匹配字符开头,若指定flags MULTILINE,这种也可以匹配上(r”^a”,”\nabc\neee”,flag=re.MULTILINE)

$ 匹配字符串结尾,或e.search(”foo$”,”bfoo\nnsdfsf”,flags=re.MULTILINE).group()也可以

* 匹配*号前的字符0次或多次,re.findall(“ab*”,”cabb3abcbbac”) 结果为[‘abb’,’ab’,’a’]

+ 匹配前一个字符1次或多次,re.findall("ab+","ab+cd+abb+bba")       ['ab', 'abb']

? 匹配前一个字符1次或0次

{m}匹配前一个字符m次 re.findall("b{3}","ab+cd+abbb+bba") ['bbb']

{n,m} 匹配前一个字符n到m次 re.findall("b{1,2}","ab+cd+abbb+bba") ['b', 'bb', 'b', 'bb'] 后边加问好是匹配最少 不加则是最多

| 匹配|左或|右的字符 re.findall("b|c","ab+cd+abbb+bba") ['b', 'c', 'b', 'b', 'b', 'b', 'b']

(...)分组匹配

\A 只从字符开头匹配

\Z 匹配字符结尾 同$

\d 匹配数字0-9

\D 匹配非数字

\w 匹配[A-Za-z0-9]

\W匹配非[A-Za-z0-9]

\s 匹配空白字符。\t \n \r

\S匹配除了空白字符。\t \n \r

 (?P<name>…)分组匹配

匹配实例

1.创建匹配对象compile方法

import re
a = re.compile(r'\d+')
a1 = a.search('gfd12341ahvcnxjbkafa')
print(a1.group())      # .group()直接输出结果,而不是返回对象

结果

12341

2.从头开始匹配 match方法

import re
a = re.match("^w.+", "wdasfdsafdsa1223fdssfd33311")
b = re.match("^[a-z]+", "wdasfdsafdsa1223fdssfd33311")
c = re.search("R[a-zA-z]+a", "wdasfdsafdsa1223fdssfd33311")
print(a)
print(b)
print(c)

结果如下

<_sre.SRE_Match object; span=(0, 27), match='wdasfdsafdsa1223fdssfd33311'>
<_sre.SRE_Match object; span=(0, 12), match='wdasfdsafdsa'>
None

3.匹配包含search方法

import re
a = re.search("[a-z]+","abcdefg12345")

print(a.group())

结果如下

abcdefg

4.管道匹配多个分组 |

import re
hero = re.compile(r'ABC|DEF')
m1 = hero.search('ABC hehe ABC')
print(m1.group())
m2 = hero.search('DEF hehe ABC')
print(m2.group())

结果如下

ABC
DEF

5.分组匹配 () 和group

import re

phoneNum = re.compile(r'(\d\d\d)-(\d\d\d-\d\d\d\d)')
mo = phoneNum.search('my number is 415-555-4242')
print(mo.group(1))          #输出第一个组
print(mo.group(2))          #输出第二个组
print(mo.group(0))          #输出所有
print(mo.group())            #输出所有

结果

415
555-4242
415-555-4242
415-555-4242

6.用问号实现可选匹配

import re
b = re.compile(r'Bat(wo)?man')
mo = b.search('The Adventures of Batman')
print(mo.group())
mo1 = b.search('The Adventures of Batwoman')
print(mo1.group())

结果

Batman

Batwoman

7.用星号匹配零次或多次

import re

b = re.compile(r'Bat(wo)*man')
mo = b.search('The Adventures of Batman')
print(mo.group())
mo1 = b.search('The Adventures of Batwoman')
print(mo1.group())
mo2 = b.search('The Adventures of Batwowowowowoman')
print(mo2.group())

结果

Batman
Batwoman
Batwowowowowoman

import re

b = re.compile(r'Bat(wo)+man')
mo = b.search('The Adventures of Batwoman')
print(mo.group())
mo1 = b.search('The Adventures of Batwoman')
print(mo1.group())
mo2 = b.search('The Adventures of Batwowowowowoman')
print(mo2.group())

 

结果

Batwoman

Batwoman

Batwowowowowoman

猜你喜欢

转载自www.cnblogs.com/wsy1030/p/8961414.html