HuiHsi

Python正则匹配

 

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

re.search(pattern, string, flags=0)
Flags可选为下面的基业
简写 全名 注释
I IGNORECASE 忽略大小写
M MULTILINE 多行模式
S DOTALL 单选模式——点任意匹配模式
L LOCALE 使预定字符类 \w \W \b \B \s \S 取决于当前区域设定
U UNICODE 使预定字符类 \w \W \b \B \s \S \d \D 取决于unicode定义的字符属性
X VERBOSE 详细模式。该模式下正则表达式可以是多行,忽略空白字符,并可以加入注释

 

#!/usr/bin/python3
import re

line = "Cats are smarter than dogs"

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!!")

 

发表于 2016-07-26 15:06  Johanan  阅读(129)  评论(0编辑  收藏  举报
 

分类:

技术点:

相关文章:

  • 2021-09-17
  • 2017-12-19
  • 2021-12-18
  • 2021-12-18
  • 2021-09-07
  • 2021-09-07
  • 2021-12-28
  • 2021-12-18
猜你喜欢
  • 2021-09-07
  • 2021-10-08
  • 2021-09-07
  • 2021-09-17
  • 2021-12-28
  • 2021-09-07
相关资源
相似解决方案