正则表达式 重点部分总结

 

ret=re.split("d+","eva3egon4yuan")
print(ret) #结果 : ['eva', 'egon', 'yuan']
ret=re.split("(d+)","eva3egon4yuan")
print(ret) #结果 : ['eva', '3', 'egon', '4', 'yuan']
#在匹配部分加上()之后所切出的结果是不不同的,
#没有()的没有保留留所匹配的项,但是有()的却能够保留留了了匹配的项,
#这个在某些需要保留留匹配部分的使⽤用过程是⾮非常重要的。

re模块是python提供的⼀一套关于处理理正则表达式的模块. 核⼼心功能有四个:
1. findall 查找所有. 返回list
lst = re.findall("m", "mai le fo len, mai ni mei!")
print(lst) # ['m', 'm', 'm']
lst = re.findall(r"d+", "5点之前. 你要给我5000万")
print(lst) # ['5', '5000']
2. search 会进⾏行行匹配. 但是如果匹配到了了第⼀一个结果. 就会返回这个结果. 如果匹配不
上search返回的则是None
ret = re.search(r'd', '5点之前. 你要给我5000万').group()
print(ret) # 5
3. match 只能从字符串串的开头进⾏行行匹配
ret = re.match('a', 'abc').group()
print(ret) # a
4. finditer 和findall差不多. 只不过这时返回的是迭代器
it = re.finditer("m", "mai le fo len, mai ni mei!")
for el in it:
print(el.group()) # 依然需要分组
5. 其他操作
ret = re.split('[ab]', 'qwerafjbcd') # 先按'a'分割得到'qwer'和'fjbcd',在
对'qwer'和'fjbcd'分别按'b'分割
print(ret) # ['qwer', 'fj', 'cd']
ret = re.sub(r"d+", "_sb_", "alex250taibai250wusir250ritian38") # 把字符串串中
的数字换成__sb__
print(ret) # alex_sb_taibai_sb_wusir_sb_ritian_sb_
ret = re.subn(r"d+", "_sb_", "alex250taibai250wusir250ritian38") # 将数字替
换成'__sb__',返回元组(替换的结果,替换了了多少次)
print(ret) # ('alex_sb_taibai_sb_wusir_sb_ritian_sb_', 4)
obj = re.compile(r'd{3}') # 将正则表达式编译成为⼀一个 正则表达式对象, 规则要匹配的
是3个数字
ret = obj.search('abc123eeee') # 正则表达式对象调⽤用search, 参数为待匹配的字符串串
print(ret.group()) # 结果: 123

 

 

[]: 括号中可以放任意一个字符,一个中括号代表一个字符

# - 在[]中表示范围,如果想要匹配上- 那么这个-符号不能放在中间.

# ^ 在[]中表示取反的意思.

.* 贪婪匹配 从头到尾. 从字符串左边第一个a开始,到最后一个b结束

.*? 非贪婪匹配,此时的?不是对左边的字符进行0次或者1次的匹配,从左边第一个a开始到左边第一个b结束,然后接着找…….

 

print(re.findall('compan(y|ies)','Too many companies have gone bankrupt, and the next one is my company'))
['ies', 'y']
print(re.findall('compan(?:y|ies)','Too many companies have gone bankrupt, and the next one is my company'))
分组() 中加入?: 表示将整体匹配出来而不只是()里面的内容。
['companies', 'company']

 
sub替换



# import re # ret = re.finditer('d', 'ds3sy4784a') #finditer返回一个存放匹配结果的迭代器 # print(ret) # <callable_iterator object at 0x10195f940> # print(next(ret).group()) #查看第一个结果 # print(next(ret).group()) #查看第二个结果 # print([i.group() for i in ret]) #查看剩余的结果






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 s S 取决于当前区域设定 5).re.U(UNICODE): 使预定字符类 w W  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*ow*',text) #查找有o的单词 #输出结果为:['JGod', 'handsome', 'boy'] #利用compile生成一个规则模式吧,然后利用findall将某一个对象内容进行匹配。,合适则输出符合规则的内容 regex=re.compile(r'w*ow*') 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*whw*',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*whw*",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*whw*",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()方法类似
  1.  
    import re
  2.  
    content='Where are you from? You look so hansome.'
  3.  
    regex=re.compile(r'w*somw*')
  4.  
    m=regex.search(content)
  5.  
    if m:
  6.  
    print m.group(0)
  7.  
    else:
  8.  
    print "Not found"
#相当于:
import re
m=re.search(r'w*somw*','Where are you from? You look so handsome.',re.I)
if m:
    print m.group(0)
else:
    print "not found"
原文地址:https://www.cnblogs.com/anthony-wang0228/p/10587024.html