Loading

re模块

  • 函数
re.match(pattern, string, flags=0),pattern为匹配的正则表达式,string为要匹配的字符串
如果不是起始位置就匹配成功,match()就会返回none
如果从起始位置匹配成功,其就会返回一个匹配对象
import re
print(re.match('www', 'www.runoob.com').span())  # 在起始位置匹配
print(re.match('com', 'www.runoob.com'))         # 不在起始位置匹配

# (0, 3)
# None

匹配的对象具有group属性,其参数为num,可以指定匹配的组号

groups()属性返回所有匹配的字符串的元组

import re
 
line = "Cats are smarter than dogs"
# .* 表示任意匹配除换行符(\n、\r)之外的任何单个或多个字符
matchObj = re.match( r'(.*) are (.*?) .*', line, re.M|re.I)
 
if matchObj:
   print ("matchObj.group() : ", matchObj.group())
   print ("matchObj.group(1) : ", matchObj.group(1))
   print ("matchObj.group(2) : ", matchObj.group(2))
else:
   print ("No match!!")

# matchObj.group() :  Cats are smarter than dogs
# matchObj.group(1) :  Cats
# matchObj.group(2) :  smarter
re.search(pattern, string, flags=0),pattern为匹配的正则表达式,string为要匹配的字符串
其会扫描整个字符串并返回第一个成功的匹配对象
与之前的区别就是,其会匹配所有的位置,而不只是从起始位置开始
re.sub(pattern, repl, string, count=0, flags=0),
 
posted @ 2020-11-04 18:19  lixin2020  阅读(94)  评论(0)    收藏  举报