python正则表达式简要

python 中使用正则表达式

  • re.match只匹配字符串的开始,如果字符串开始不符合正则表达式,则匹配失败,函数返回None;而re.search匹配整个字符串,直到找到一个匹配。
import re
x= re.search('oob', 'www.runoob.com') #返回的是个一个元组,匹配下标索引
#如果re.search没有匹配上,则span函数会报错,需要先使用if条件判断一下是否是None对象
if x is not None:
    y=x.group(0)
else:
    y="NA"
y
#y="www"[x.span()[0]:x.span()[1]]
'oob'
#python中正则表达式使用group来分组
line = "Cats are smarter than dogs"
 
matchObj = re.match( r'(.*) are (.*?) .*', line, re.M|re.I)
 
if matchObj:
   y1=matchObj.group()
   y2=matchObj.group(1)
   y3=matchObj.group(2)
else:
   y1="No match!!"
[y1,y2,y3]
['Cats are smarter than dogs', 'Cats', 'smarter']
if (re.match(r'w{3}', 'www.runoob.com')):
    x="yes"
else:
    x="no"
x
#re.match 和 re.search第一个参数为正则表达式,第二个为需要匹配的文本,返回值的类型为逻辑类型
#match只能匹配从头开始
'yes'
if (re.search(r'abc', 'www.runoob.com')):
    x="yes"
else:
    x="no"
x
'no'
  • 使用findall函数
text = "foo    bar\t baz  \tquxfo"
re.split('\s+', text)
re.findall(pattern=r"fo{1,2}",string=text)
#findall返回的是一个列表数组,找出所有的匹配项
['foo', 'fo']
  • 检索和替换,使用re.sub函数
phone = "2004-959-559 # 这是一个国外电话号码"
 
# 删除字符串中的 Python注释 
num1 = re.sub(r'#.*$', "", phone)#第一个参数为pattern正则,第二个参数为需要替换的字符,第三个参数为text文本
 
# 删除非数字(-)的字符串 
num2 = re.sub(r'\D', "", phone)

num1,num2
('2004-959-559 ', '2004959559')

import re
x=star
def replace(n):
    if n is not None:
        return re.sub(string=n,pattern="演: ",repl="")
 
x=map(replace,x)    
for i in x:
    print(i)

你可能感兴趣的:(python正则表达式简要)