正则表达式

python 正则表达式

学习自莫烦python

导入模块

import re  

简单python匹配

# matching string  
pattern1 = "cat"  
pattern2 = "bird"  
string = "dog rans to cat"  
print(pattern1 in string)  
print(pattern2 in string)  
True  
False  

使用正则寻找匹配

#regular experssion  
pattern1 = "cat"  
pattern2 = "dob"  
string = "dog runs to cat"  
print(re.search(pattern1, string))  
print(re.search(pattern2, string))  
<re.Match object; span=(12, 15), match='cat'>  
None  

匹配多种可能 使用[]

# numtiple patterns ("run" or "ran")  
ptn = r"r[au]n" # r 表示转义, []之中存放多种字符,匹配时只要存在一个便匹配到了  
string = "dog rans to cat"  
print(re.search(ptn, string))  
<re.Match object; span=(4, 7), match='ran'>  

匹配更多种可能

# continue  
print(re.search(r"r[A-Z]n", string))  
print(re.search(r"r[a-z]n", string))  
print(re.search(r"r[0-9]n", string))  
print(re.search(r"r[0-9a-z]n", string))  
None  
<re.Match object; span=(4, 7), match='ran'>  
None  
<re.Match object; span=(4, 7), match='ran'>  

特殊类型匹配

数字

# \d : decimal digit 所有数字  
print(re.search(r"r\dn", "run r4n"))  
# \D : any non_decimal digit 不是数字的所有字符  
print(re.search(r"r\Dn", "run r4n"))  
<re.Match object; span=(4, 7), match='r4n'>  
<re.Match object; span=(0, 3), match='run'>  

空白

# \s : any white space [\t\n\r\f\v] 所有空白符,制表符,空格,回车等  
print(re.search(r"r\sn", 'run r n'))  
# \S : opposite to \s, any non_white space 所用可显示字符  
print(re.search(r"r\Sn", "run r n"))  
<re.Match object; span=(4, 7), match='r n'>  
<re.Match object; span=(0, 3), match='run'>  

所有字母数字和下划线”_”

# \w : [a-zA-Z0-9_]  
print(re.search(r"r\wn", "r\nn r4n"))  
# \W : opposite to \w 与\w 相反  
print(re.search(r"r\Wn", "r\nn r_n"))  
<re.Match object; span=(4, 7), match='r4n'>  
<re.Match object; span=(0, 3), match='r\nn'>  

空白字符

# \b :empty string (only at the start or end of the word) 在紧贴单词前后的空白  
print(re.search(r"\bruns\b", "dog runs to the cat"))  
# \B : empty string (but not at the start or end of a word) 紧贴单词前后没有空白  
print(re.search(r"\Bruns\B", "dogrunsto  the cat"))  
<re.Match object; span=(4, 8), match='runs'>  
<re.Match object; span=(3, 7), match='runs'>  

特殊字符 任意字符

# \\ : match \  匹配反斜杠  
print(re.search(r"runs\\", "runs\ to me"))  
# . : metch anything (except \n) 除了换行符之外的所有字符  
print(re.search(r"r.n", "r[n to me"))  
<re.Match object; span=(0, 5), match='runs\\'>  
<re.Match object; span=(0, 3), match='r[na]s'>  

句尾句首

# ^ : match line begining #匹配句首  
print(re.search(r"^dog", "dog runs to cat"))  
print(re.search(r"^dog", "cat runs to dog"))  
# $ : match line ending 匹配句尾  
print(re.search(r"cat$", "dog runs to cat"))  
print(re.search(r"cat$", "cat runs to dog"))  
<re.Match object; span=(0, 3), match='dog'>  
None  
<re.Match object; span=(12, 15), match='cat'>  
None  

是否

# ? : may or may not occur # 括号里的有就匹配,没有也匹配只要括号外的有  
print(re.search(r"Mon(day)?", "Monday"))  
print(re.search(r"Mon(day)?", "Mon"))  
<re.Match object; span=(0, 6), match='Monday'>  
<re.Match object; span=(0, 3), match='Mon'>  

多行匹配

# multi-line  
string = '''  
dog runs to cat.  
I run to dof.  
'''  
print(re.search(r"^I", string)) #多行直接匹配句首没法匹配  
print(re.search(r"^I", string, flags=re.M)) #flags=r.M 表示让其把每行当成单独的来匹配  
None  
<re.Match object; span=(18, 19), match='I'>  

0或多次

# * :occur 0 or more times  
print(re.search(r"ab*", "a"))  
print(re.search(r"ab*", "abbbb"))  
<re.Match object; span=(0, 1), match='a'>  
<re.Match object; span=(0, 5), match='abbbb'>  

一或多次

# + :occur 1 or more times  
print(re.search(r"ab+", "a"))  
print(re.search(r"ab+", "abbb"))  
None  
<re.Match object; span=(0, 4), match='abbb'>  

可选次数

# {n, m} : occur n to m times 出现了n到m之间的次数  
print(re.search(r"ab{2,10}", "a"))  
print(re.search(r"ab{2,10}", "abbbb")) # 注意{}之中不要添加空格了,只有数字  
None  
<re.Match object; span=(0, 5), match='abbbb'>  

group 组

# group  
match = re.search(r"(\d+), Data: (.+)", "ID: 021523, Data: Feb/12/2017") #()里的东西相当于是一个组  
print(match)  
print(match.group()) #返回所用东西 7  
print(match.group(1))  
print(match.group(2))  
<re.Match object; span=(4, 29), match='021523, Data: Feb/12/2017'>  
021523, Data: Feb/12/2017  
021523  
Feb/12/2017  
#自定义每一组的名字  
match = re.search(r"(?P<id>\d+), Data: (?P<date>.+)", "ID: 021523, Data: Feb/12/2017")  
print(match)  
print(match.group('id'))  
print(match.group('date'))  
<re.Match object; span=(4, 29), match='021523, Data: Feb/12/2017'>  
021523  
Feb/12/2017  

寻找所有匹配 findall

# findall  
print(re.findall(r"r[ua]n", "run ran ren"))  
['run', 'ran']  
# | : or  
print(re.findall(r"run|ran", "run ran ren"))  #仅匹配|两侧的,如果有括号进匹配括号内的|的两侧的东西  
['run', 'ran']  

替换(查找并替换)

# re.sub() replace  
print(re.sub(r"r[au]ns", "catches", "dog runs to cat"))  
dog catches to cat  

分裂 split

# re.split()  
print(re.split(r"[,;\.]", "a;b,c.d;e")) #以【】中的为分隔符  
['a', 'b', 'c', 'd', 'e']  

compile

# compile  
compiled_re = re.compile(r"r[ua]n") #相当于先将条件格式化  
print(compiled_re.search("dog ran to cat"))  
<re.Match object; span=(4, 7), match='ran'>  

![Alt](https://morvanzhou.github.io/static/results/basic/13-10-01.png =150x300)Alt

写个博客不容易,可怜可怜博主,点个广告再走呗(✿◕‿◕✿)。


   转载规则


《正则表达式》 ZS 采用 知识共享署名 4.0 国际许可协议 进行许可。
 上一篇
模拟除法 模拟除法
PTA 乙级1017A除以B(模拟除法) ,有点意思,题目不是很难就是很难。长点心,想的全面点。 题目 本题要求计算 A/B,其中 A 是不超过 1000 位的正整数,B 是 1 位正整数。你需要输出商数 Q 和余数 R,使得 A=
2019-02-22
下一篇 
超长字符串的商 超长字符串的商
原理 例如{1, 2, 3, 4, 5, 6, 7,8}要向左平移2个单位 先将前两个数据{1,2}反转为{2,1} 之后将后面的数据{3,4,5,6,7,8}反转为{8,7,6,5,4,3} 两个片段的相对位置没有改变得到了
2019-02-18
  目录