python正则表达式


re.match(pattern, string, flags=0):从头匹配,如果不是起始位置匹配成功的话,match()就返回none。
re.search(pattern, string, flags=0):扫描整个字符串并返回第一个成功的匹配
re.findall():找到所有要匹配的字符并返回列表格式
re.split():将匹配到的格式当做分割点对字符串分割成列表
re.sub(pattern, repl, string, count=0, flags=0):替换匹配到的字符
re.compile():用于编译正则表达式,生成一个正则表达式( Pattern )对象

re.match函数

从字符串的起始位置匹配一个模式,如果不是起始位置匹配成功的话,match()就返回none。

函数语法:

re.match(pattern, string, flags=0)

import re

line = "Cats are smarter than dogs"

matchObj = re.match( r'(.*) are (.*?) .*', line, re.M|re.I)

if matchObj:
    print(matchObj)
    print("matchObj.group() : "+matchObj.group())
    print("matchObj.group(1) : "+matchObj.group(1))
    print("matchObj.group(2) : "+matchObj.group(2))
    print "matchObj.groups(): ", matchObj.groups()
else:
    print "No match!!"

返回如下:

<_sre.SRE_Match object at 0x1046934f8>
matchObj.group() : Cats are smarter than dogs
matchObj.group(1) : Cats
matchObj.group(2) : smarter
matchObj.groups():  ('Cats', 'smarter')

re.search函数

import re

line = "Cats are smarter than dogs"

matchObj = re.search( r'(.*) are (.*?) .*', line, re.M|re.I)

if matchObj:
    print(matchObj)
    print("matchObj.group() : "+matchObj.group())
    print("matchObj.group(1) : "+matchObj.group(1))
    print("matchObj.group(2) : "+matchObj.group(2))
    print "matchObj.groups(): ", matchObj.groups()
else:
    print "No match!!"

结果如下:

<_sre.SRE_Match object at 0x1034554f8>
matchObj.group() : Cats are smarter than dogs
matchObj.group(1) : Cats
matchObj.group(2) : smarter
matchObj.groups():  ('Cats', 'smarter')

re.match与re.search的区别
re.match与re.search的方法都是一样的,唯一的区别:

  • re.match只匹配字符串的开始,如果字符串开始不符合正则表达式,则匹配失败,函数返回None;
  • re.search匹配整个字符串,直到找到一个匹配。

re.findall函数

在字符串中找到正则表达式所匹配的所有子串,并返回一个列表,如果没有找到匹配的,则返回空列表。
match 和 search 是匹配一次 ,而findall 匹配所有
语法格式为:
findall(string[, pos[, endpos]])

import re

m = re.findall("[0-9]", "alex1rain2jack3helen rachel8")
print(m)
contactInfo = 'Oldboy School, Beijing Changping Shahe: 010-8343245 hahhaha'
match = re.findall(r'(\D+), (\D+): (\S+).*', contactInfo)
print(match)
match = re.findall(r'\D+, \D+: \S+.*', contactInfo)
print(match)

结果如下:

['1', '2', '3', '8']
[('Oldboy School', 'Beijing Changping Shahe', '010-8343245')]
['Oldboy School, Beijing Changping Shahe: 010-8343245 hahhaha']

findall()返回的是括号所匹配到的结果,多个括号就会返回多个括号分别匹配到的结果,如果没有括号就返回就返回整条语句所匹配到的结果。

re.split()函数

按照能够匹配的子串将字符串分割后返回列表,它的使用形式如下:
re.split(pattern, string[, maxsplit=0, flags=0])

import re

m = re.split("[0-9]", "alex1rain2jack3helen rachel8")
print(m)

结果如下:

['alex', 'rain', 'jack', 'helen rachel', '']

re.sub()函数

re.sub(pattern, repl, string, count=0, flags=0):替换匹配到的字符

  • pattern : 正则中的模式字符串。
  • repl : 替换的字符串,也可为一个函数。
  • string : 要被查找替换的原始字符串。
  • count : 模式匹配后替换的最大次数,默认 0 表示替换所有的匹配。
import re

m=re.sub("[0-9]","|", "alex1rain2jack3helen rachel8",count=2)
print(m)

结果如下:

alex|rain|jack3helen rachel8

re.compile()

用于编译正则表达式,生成一个正则表达式( Pattern )对象,供 match() 和 search() 这两个函数使用。
语法格式为:
re.compile(pattern[, flags])

import re

p = re.compile("(.*) are (.*?) .*")
m = p.match("Cats are smarter than dogs")
print(m.group())

结果如下:

Cats are smarter than dogs
p = re.compile("(.*) are (.*?) .*")
m = p.match("Cats are smarter than dogs")

m = re.match( r'(.*) are (.*?) .*', "Cats are smarter than dogs")

上面两种方式,效果是一样的,区别在于,第一种方式是提前对要匹配的格式进行了编译对匹配公式进行解析),这样再去匹配的时候就不用在编译匹配的格式,第2种简写是每次匹配的时候都要进行一次匹配公式的编译,所以,如果需要循环匹配时,建议用第一种方式,速度会快点。

分组匹配

import re

contactInfo = 'Oldboy School, Beijing Changping Shahe: 010-8343245 hahhaha'
match = re.search(r'(?P<last>\D+), (?P<first>\D+): (?P<phone>\S+).*', contactInfo)
print(match.group('last'))
print(match.group('first'))
print(match.group('phone'))
print(match.groupdict())
print(match.group())
print(match.groups())

结果如下:

Oldboy School
Beijing Changping Shahe
010-8343245
{'phone': '010-8343245', 'last': 'Oldboy School', 'first': 'Beijing Changping Shahe'}
Oldboy School, Beijing Changping Shahe: 010-8343245 hahhaha
('Oldboy School', 'Beijing Changping Shahe', '010-8343245')

正则表达式修饰符 - 可选标志

正则表达式可以包含一些可选标志修饰符来控制匹配的模式。修饰符被指定为一个可选的标志。多个标志可以通过按位 OR(|) 它们来指定。如 re.I | re.M 被设置成 I 和 M 标志:

  • re.I 忽略大小写
  • re.L 表示特殊字符集 \w, \W, \b, \B, \s, \S 依赖于当前环境,做本地化识别(locale-aware)匹配
  • re.M 多行匹配
  • re.S 使 . 匹配包括换行在内的所有字符(. 不包括换行符)
  • re.U 根据Unicode字符集解析字符。这个标志影响 \w, \W, \b, \B.
  • re.X 为了增加可读性,忽略空格和 # 后面的注释
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值