Python中正则模块re.compile、re.match及re.search函数用法

import re
help(re.compile)
'''
输出结果为:
Help on function compile in module re:

compile(pattern, flags=0)
Compile a regular expression pattern, returning a pattern object.
通过help可知:编译一个正则表达式模式,返回一个模式对象。
'''

'''
第二个参数flags是匹配模式,可以使用按位或’|’表示同时生效,也可以在正则表达式字符串中指定。
Pattern对象是不能直接实例化的,只能通过compile方法得到。匹配模式有:
1).re.I(re.IGNORECASE): 忽略大小写
2).re.M(MULTILINE): 多行模式,改变’^’和’$’的行为
3).re.S(DOTALL): 点任意匹配模式,改变’.’的行为
4).re.L(LOCALE): 使预定字符类 \w \W \b \B \s \S 取决于当前区域设定
5).re.U(UNICODE): 使预定字符类 \w \W \b \B \s \S \d \D 取决于unicode定义的字符属性
6).re.X(VERBOSE): 详细模式。这个模式下正则表达式可以是多行,忽略空白字符,并可以加入注释
'''

text="JGod is a handsome boy ,but he is a ider"
print re.findall(r'\w*o\w*',text) #查找有o的单词
#输出结果为:['JGod', 'handsome', 'boy']

#利用compile生成一个规则模式吧,然后利用findall将某一个对象内容进行匹配。,合适则输出符合规则的内容
regex=re.compile(r'\w*o\w*')
print regex.findall(text)
#>>> ['JGod', 'handsome', 'boy']

test1="who you are,what you do,When you get get there? What is time you state there?"
regex1=re.compile(r'\w*wh\w*',re.IGNORECASE)
wh=regex1.findall(test1)
print wh
#>>> ['who', 'what', 'When', 'What']

'''
re正则表达式模块还包括一些有用的操作正则表达式的函数。下面主要介绍match函数以及search函数。
定义: re.match 尝试从字符串的开始匹配一个模式。
原型:
re.match(pattern, string, flags)
第一个参数是正则表达式,如果匹配成功,则返回一个Match,否则返回一个None;
第二个参数表示要匹配的字符串;
第三个参数是标致位,用于控制正则表达式的匹配方式,如:是否区分大小写,多行匹配等等。

函数的返回值为真或者假。
例如:match(‘p’,’python’)返回值为真;match(‘p’,’www.python.org’)返回值为假。

定义:re.search会在给定字符串中寻找第一个匹配给定正则表达式的子字符串。

函数的返回值:如果查找到则返回查找到的值,否则返回为None。

原型:
re.search(pattern, string, flags)

每个参数的含意与re.match一样。
'''
#re.match的例子1
import re
your_love=re.match("wh","What are you doing? who is you mate?",re.I)
if your_love:
print "you are my angle"
else:
print "i lose you "
#相当于:
print "*"*100 #便于区分
import re
content="What are you doing? who is your mate?"
regu_cont=re.compile("\w*wh\w*",re.I)
yl=regu_cont.match(content)
if yl:
print yl.group(0)
else:
print "what happen?"
解析:首先创造了需要正则表达式匹配的字符串content;
接着利用re.compile()来创建了我们所需要的匹配规则,创建了模式对象regu_cont;
yl用来接收对内容content字符串进行regu_cont正则表达式实现match函数的结果
如果有yl不为空,则使用m.group(index)输出查找到的子字符串 否则(返回值为None) print “what happen?”


match例子2

'''
match如果查找到结果, 将返回一个 MatchObject,你可以查询 MatchObject 关于匹配字符串的相关信息了。MatchObject 实例也有几个方法和属性;最重要的那些如下所示:
group() 返回被 RE 匹配的字符串
start() 返回匹配开始的位置
end() 返回匹配结束的位置
span() 返回一个元组包含匹配 (开始,结束) 的位置
'''
import re
content="What are you doing? who is your mate?"
regu_cont=re.compile("\w*wh\w*",re.I)
yl=regu_cont.match(content)
if yl:
print yl.group(0)
else:
print "pass the test"
print yl.group()
print yl.start()
print yl.end()
print yl.span()

执行结果为:
What
What
0
4
(0, 4)


#search()方法与match()方法类似
import re
content='Where are you from? You look so hansome.'
regex=re.compile(r'\w*som\w*')
m=regex.search(content)
if m:
    print m.group(0) else: print "Not found"

#相当于:
import re
m=re.search(r'\w*som\w*','Where are you from? You look so handsome.',re.I)
if m:
print m.group(0)
else:
print "not found"

re 模块官方说明文档

正则匹配的时候,第一个字符是 r,表示 raw string 原生字符,意在声明字符串中间的特殊字符不用转义。

比如表示 ‘\n',可以写 r'\n',或者不适用原生字符 ‘\n'。

推荐使用 re.match

re.compile() 函数

编译正则表达式模式,返回一个对象。可以把常用的正则表达式编译成正则表达式对象,方便后续调用及提高效率。

re.compile(pattern, flags=0)

  • pattern 指定编译时的表达式字符串
  • flags 编译标志位,用来修改正则表达式的匹配方式。支持 re.L|re.M 同时匹配

flags 标志位参数

re.I(re.IGNORECASE) 
使匹配对大小写不敏感

re.L(re.LOCAL)  
做本地化识别(locale-aware)匹配

re.M(re.MULTILINE)  
多行匹配,影响 ^ 和 $

re.S(re.DOTALL) 
使 . 匹配包括换行在内的所有字符

re.U(re.UNICODE)
根据Unicode字符集解析字符。这个标志影响 \w, \W, \b, \B.

re.X(re.VERBOSE)
该标志通过给予你更灵活的格式以便你将正则表达式写得更易于理解。

示例:

?
1
2
3
4
5
6
7
import re
content = 'Citizen wang , always fall in love with neighbour,WANG'
rr = re. compile (r 'wan\w' , re.I) # 不区分大小写
print ( type (rr))
a = rr.findall(content)
print ( type (a))
print (a)

findall 返回的是一个 list 对象

<class '_sre.SRE_Pattern'>
<class 'list'>
['wang', 'WANG']

re.match() 函数

总是从字符串‘开头曲匹配',并返回匹配的字符串的 match 对象 <class '_sre.SRE_Match'>。

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

  • pattern 匹配模式,由 re.compile 获得
  • string 需要匹配的字符串
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import re
pattern = re. compile (r 'hello' )
a = re.match(pattern, 'hello world' )
b = re.match(pattern, 'world hello' )
c = re.match(pattern, 'hell' )
d = re.match(pattern, 'hello ' )
if a:
   print (a.group())
else :
   print ( 'a 失败' )
if b:
   print (b.group())
else :
   print ( 'b 失败' )
if c:
   print (c.group())
else :
   print ( 'c 失败' )
if d:
   print (d.group())
else :
   print ( 'd 失败' )

hello
b 失败
c 失败
hello

match 的方法和属性

参考链接

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import re
str = 'hello world! hello python'
pattern = re. compile (r '(?P<first>hell\w)(?P<symbol>\s)(?P<last>.*ld!)' ) # 分组,0 组是整个 hello world!, 1组 hello,2组 ld!
match = re.match(pattern, str )
print ( 'group 0:' , match.group( 0 )) # 匹配 0 组,整个字符串
print ( 'group 1:' , match.group( 1 )) # 匹配第一组,hello
print ( 'group 2:' , match.group( 2 )) # 匹配第二组,空格
print ( 'group 3:' , match.group( 3 )) # 匹配第三组,ld!
print ( 'groups:' , match.groups())  # groups 方法,返回一个包含所有分组匹配的元组
print ( 'start 0:' , match.start( 0 ), 'end 0:' , match.end( 0 )) # 整个匹配开始和结束的索引值
print ( 'start 1:' , match.start( 1 ), 'end 1:' , match.end( 1 )) # 第一组开始和结束的索引值
print ( 'start 2:' , match.start( 1 ), 'end 2:' , match.end( 2 )) # 第二组开始和结束的索引值
print ( 'pos 开始于:' , match.pos)
print ( 'endpos 结束于:' , match.endpos) # string 的长度
print ( 'lastgroup 最后一个被捕获的分组的名字:' , match.lastgroup)
print ( 'lastindex 最后一个分组在文本中的索引:' , match.lastindex)
print ( 'string 匹配时候使用的文本:' , match.string)
print ( 're 匹配时候使用的 Pattern 对象:' , match.re)
print ( 'span 返回分组匹配的 index (start(group),end(group)):' , match.span( 2 ))

返回结果:

group 0: hello world!
group 1: hello
group 2:  
group 3: world!
groups: ('hello', ' ', 'world!')
start 0: 0 end 0: 12
start 1: 0 end 1: 5
start 2: 0 end 2: 6
pos 开始于: 0
endpos 结束于: 25
lastgroup 最后一个被捕获的分组的名字: last
lastindex 最后一个分组在文本中的索引: 3
string 匹配时候使用的文本: hello world! hello python
re 匹配时候使用的 Pattern 对象: re.compile('(?P<first>hell\\w)(?P<symbol>\\s)(?P<last>.*ld!)')
span 返回分组匹配的 index (start(group),end(group)): (5, 6)

re.search 函数

对整个字符串进行搜索匹配,返回第一个匹配的字符串的 match 对象。

re.search(pattern, string[, flags=0])

  • pattern 匹配模式,由 re.compile 获得
  • string 需要匹配的字符串
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import re
str = 'say hello world! hello python'
pattern = re. compile (r '(?P<first>hell\w)(?P<symbol>\s)(?P<last>.*ld!)' ) # 分组,0 组是整个 hello world!, 1组 hello,2组 ld!
search = re.search(pattern, str )
print ( 'group 0:' , search.group( 0 )) # 匹配 0 组,整个字符串
print ( 'group 1:' , search.group( 1 )) # 匹配第一组,hello
print ( 'group 2:' , search.group( 2 )) # 匹配第二组,空格
print ( 'group 3:' , search.group( 3 )) # 匹配第三组,ld!
print ( 'groups:' , search.groups())  # groups 方法,返回一个包含所有分组匹配的元组
print ( 'start 0:' , search.start( 0 ), 'end 0:' , search.end( 0 )) # 整个匹配开始和结束的索引值
print ( 'start 1:' , search.start( 1 ), 'end 1:' , search.end( 1 )) # 第一组开始和结束的索引值
print ( 'start 2:' , search.start( 1 ), 'end 2:' , search.end( 2 )) # 第二组开始和结束的索引值
print ( 'pos 开始于:' , search.pos)
print ( 'endpos 结束于:' , search.endpos) # string 的长度
print ( 'lastgroup 最后一个被捕获的分组的名字:' , search.lastgroup)
print ( 'lastindex 最后一个分组在文本中的索引:' , search.lastindex)
print ( 'string 匹配时候使用的文本:' , search.string)
print ( 're 匹配时候使用的 Pattern 对象:' , search.re)
print ( 'span 返回分组匹配的 index (start(group),end(group)):' , search.span( 2 ))

注意 re.search 和 re.match 匹配的 str 的区别

打印结果:

group 0: hello world!
group 1: hello
group 2:  
group 3: world!
groups: ('hello', ' ', 'world!')
start 0: 4 end 0: 16
start 1: 4 end 1: 9
start 2: 4 end 2: 10
pos 开始于: 0
endpos 结束于: 29
lastgroup 最后一个被捕获的分组的名字: last
lastindex 最后一个分组在文本中的索引: 3
string 匹配时候使用的文本: say hello world! hello python
re 匹配时候使用的 Pattern 对象: re.compile('(?P<first>hell\\w)(?P<symbol>\\s)(?P<last>.*ld!)')
span 返回分组匹配的 index (start(group),end(group)): (9, 10)

PS:这里再为大家提供2款非常方便的正则表达式工具供大家参考使用:

JavaScript正则表达式在线测试工具:
http://tools.jb51.net/regex/javascript

正则表达式在线生成工具:
http://tools.jb51.net/regex/create_reg

https://www.cnblogs.com/huangdongju/p/7839697.html

转载于:https://www.cnblogs.com/klb561/p/9332830.html

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: re.compile() 是 Python 正则表达式库 re 的一个函数。它的作用是将正则表达式的字符串形式编译为一个正则表达式对象,这样可以提高正则匹配的效率。使用 re.compile() 后,可以使用该对象的方法进行匹配和替换操作。 语法:re.compile(pattern[, flags]) 参数说明: - pattern:要编译的正则表达式字符串 - flags:正则表达式的标志位,可选参数,如IGNORECASE,DOTALL,MULTILINE等 返回值:返回编译后的正则表达式对象 示例: ``` import re pattern = re.compile(r'\d+') ``` 可以看出,re.compile() 函数是将正则表达式的字符串形式转化为正则表达式对象,以便使用其方法(match,search,findall...)更高效的进行正则匹配。 ### 回答2: re.compile()函数Pythonre模块的一个方法,用于将正则表达式字符串编译成模式对象。通过编译正则表达式,可以提高正则表达式的匹配效率。 re.compile(pattern, flags=0)函数接受两个参数。其,pattern是一个字符串,表示需要编译的正则表达式。flags是可选的参数,用于指定匹配模式,可以通过设置不同的标志来改变匹配的行为。 通过re.compile()函数编译后得到的模式对象可以被多次使用,避免了重复编译的开销。模式对象可以调用多个方法,如match()、search()、findall()等,来实现对字符串的匹配。 re.compile()函数还可以用于管理和测试正则表达式的性能和扩展性。通过传递不同的flags参数,可以改变正则表达式的匹配模式。例如,re.IGNORECASE可以设置不区分大小写,re.DOTALL可以匹配包括换行符在内的任意字符。 如果正则表达式的模式较为复杂或需要多次使用,使用re.compile()函数进行编译可以提高执行效率。对于大规模数据处理或复杂的字符串匹配需求,合理使用re.compile()函数可以优化程序性能。 总之,re.compile()函数Pythonre模块的一个重要方法,用于将正则表达式字符串编译成可复用的模式对象,并可以通过设置不同的flags参数来改变匹配的行为。 ### 回答3: re.compile()函数Python用于编译正则表达式模式的函数正则表达式是用来描述文本模式的一种语法,并且可以匹配、查找和替换文本特定模式的字符串。 re.compile()函数接受一个正则表达式模式作为参数,并返回一个正则表达式对象。这个对象可以用于后续的匹配操作。 使用re.compile()函数的好处是可以编译正则表达式,提高后续的匹配效率。如果要多次使用同一正则表达式进行匹配,就可以先使用re.compile()函数编译成对象,然后反复使用这个对象进行匹配操作,而不需要每次都重新编译正则表达式。 re.compile()函数还可以接受可选的标志参数,用来指定匹配模式和匹配行为。常用的一些标志参数包括re.I(忽略大小写)、re.M(多行模式)、re.S(使 '.' 匹配包括换行符在内的所有字符)等。 使用re.compile()函数的一般流程是:首先将正则表达式模式作为参数传递给re.compile()函数来编译正则表达式,并返回一个正则表达式对象;然后,使用这个对象的匹配方法,如match()、search()、findall()等,来进行具体的匹配操作。 综上所述,re.compile()函数是用于编译正则表达式模式的函数,返回一个正则表达式对象。它在实际编写和应用正则表达式时非常有用,可以提高匹配效率和灵活性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值