设为首页 收藏本站
查看: 829|回复: 0

[经验分享] re Python正则

[复制链接]

尚未签到

发表于 2018-8-7 07:10:33 | 显示全部楼层 |阅读模式
  re.compile() 生成正则对象效率最高
  # encoding: UTF-8
  import re
  # 将正则表达式编译成Pattern对象
  pattern = re.compile(r'hello')
  # 使用Pattern匹配文本,获得匹配结果,无法匹配时将返回None
  match = pattern.match('hello world!')
  if match:
  # 使用Match获得分组信息
  print match.group()
  ### 输出 ###
  # hello
  re.compile(strPattern[, flag]):
  这个方法是Pattern类的工厂方法,用于将字符串形式的正则表达式编译为Pattern对象。 第二个参数flag是匹配模式,取值可以使用按位或运算符'|'表示同时生效,比如re.I | re.M。另外,你也可以在regex字符串中指定模式,比如re.compile('pattern', re.I | re.M)与re.compile('(?im)pattern')是等价的。
  可选值有:

  •   re.I(re.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): 详细模式。这个模式下正则表达式可以是多行,忽略空白字符,并可以加入注释。以下两个正则表达式是等价的:
  1
  2
  3
  4
  a = re.compile(r"""\d +  # the integral part
  \.    # the decimal point
  \d *  # some fractional digits""", re.X)
  b = re.compile(r"\d+\.\d*")
  re提供了众多模块方法用于完成正则表达式的功能。这些方法可以使用Pattern实例的相应方法替代,唯一的好处是少写一行re.compile()代码,但同时也无法复用编译后的Pattern对象。这些方法将在Pattern类的实例方法部分一起介绍。如上面这个例子可以简写为:
  1
  2
  m = re.match(r'hello', 'hello world!')
  print m.group()
  re模块还提供了一个方法escape(string),用于将string中的正则表达式元字符如*/+/?等之前加上转义符再返回,在需要大量匹配元字符时有那么一点用。
2.2. Match
  Match对象是一次匹配的结果,包含了很多关于此次匹配的信息,可以使用Match提供的可读属性或方法来获取这些信息。
  属性:

  •   string: 匹配时使用的文本。
  •   re: 匹配时使用的Pattern对象。
  •   pos: 文本中正则表达式开始搜索的索引。值与Pattern.match()和Pattern.seach()方法的同名参数相同。
  •   endpos: 文本中正则表达式结束搜索的索引。值与Pattern.match()和Pattern.seach()方法的同名参数相同。
  •   lastindex: 最后一个被捕获的分组在文本中的索引。如果没有被捕获的分组,将为None。
  •   lastgroup: 最后一个被捕获的分组的别名。如果这个分组没有别名或者没有被捕获的分组,将为None。
  方法:

  •   group([group1, …]):
      获得一个或多个分组截获的字符串;指定多个参数时将以元组形式返回。group1可以使用编号也可以使用别名;编号0代表整个匹配的子串;不填写参数时,返回group(0);没有截获字符串的组返回None;截获了多次的组返回最后一次截获的子串。
  •   groups([default]):
      以元组形式返回全部分组截获的字符串。相当于调用group(1,2,…last)。default表示没有截获字符串的组以这个值替代,默认为None。
  •   groupdict([default]):
      返回以有别名的组的别名为键、以该组截获的子串为值的字典,没有别名的组不包含在内。default含义同上。
  •   start([group]):
      返回指定的组截获的子串在string中的起始索引(子串第一个字符的索引)。group默认值为0。
  •   end([group]):
      返回指定的组截获的子串在string中的结束索引(子串最后一个字符的索引+1)。group默认值为0。
  •   span([group]):
      返回(start(group), end(group))。
  •   expand(template):
      将匹配到的分组代入template中然后返回。template中可以使用\id或\g<id>、\g<name>引用分组,但不能使用编号0。\id与\g<id>是等价的;但\10将被认为是第10个分组,如果你想表达\1之后是字符'0',只能使用\g<1>0。
  1
  2
  3
  4
  5
  6
  7
  8
  9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  import re
  m = re.match(r'(\w+) (\w+)(?P<sign>.*)', 'hello world!')
  print &quot;m.string:&quot;, m.string
  print &quot;m.re:&quot;, m.re
  print &quot;m.pos:&quot;, m.pos
  print &quot;m.endpos:&quot;, m.endpos
  print &quot;m.lastindex:&quot;, m.lastindex
  print &quot;m.lastgroup:&quot;, m.lastgroup
  print &quot;m.group(1,2):&quot;, m.group(1, 2)
  print &quot;m.groups():&quot;, m.groups()
  print &quot;m.groupdict():&quot;, m.groupdict()
  print &quot;m.start(2):&quot;, m.start(2)
  print &quot;m.end(2):&quot;, m.end(2)
  print &quot;m.span(2):&quot;, m.span(2)
  print r&quot;m.expand(r'\2 \1\3'):&quot;, m.expand(r'\2 \1\3')
  ### output ###
  # m.string: hello world!
  # m.re: <_sre.SRE_Pattern object at 0x016E1A38>
  # m.pos: 0
  # m.endpos: 12
  # m.lastindex: 3
  # m.lastgroup: sign
  # m.group(1,2): ('hello', 'world')
  # m.groups(): ('hello', 'world', '!')
  # m.groupdict(): {'sign': '!'}
  # m.start(2): 6
  # m.end(2): 11
  # m.span(2): (6, 11)
  # m.expand(r'\2 \1\3'): world hello!
2.3. Pattern
  Pattern对象是一个编译好的正则表达式,通过Pattern提供的一系列方法可以对文本进行匹配查找。
  Pattern不能直接实例化,必须使用re.compile()进行构造。
  Pattern提供了几个可读属性用于获取表达式的相关信息:

  •   pattern: 编译时用的表达式字符串。
  •   flags: 编译时用的匹配模式。数字形式。
  •   groups: 表达式中分组的数量。
  •   groupindex: 以表达式中有别名的组的别名为键、以该组对应的编号为值的字典,没有别名的组不包含在内。
  1
  2
  3
  4
  5
  6
  7
  8
  9
  10
  11
  12
  13
  import re
  p = re.compile(r'(\w+) (\w+)(?P<sign>.*)', re.DOTALL)
  print &quot;p.pattern:&quot;, p.pattern
  print &quot;p.flags:&quot;, p.flags
  print &quot;p.groups:&quot;, p.groups
  print &quot;p.groupindex:&quot;, p.groupindex
  ### output ###
  # p.pattern: (\w+) (\w+)(?P<sign>.*)
  # p.flags: 16
  # p.groups: 3
  # p.groupindex: {'sign': 3}
  实例方法[ | re模块方法]:
  match(string[, pos[, endpos]]) | re.match(pattern, string[, flags]):

  •   这个方法将从string的pos下标处起尝试匹配pattern;如果pattern结束时仍可匹配,则返回一个Match对象;如果匹配过程中pattern无法匹配,或者匹配未结束就已到达endpos,则返回None。
      pos和endpos的默认值分别为0和len(string);re.match()无法指定这两个参数,参数flags用于编译pattern时指定匹配模式。
      注意:这个方法并不是完全匹配。当pattern结束时若string还有剩余字符,仍然视为成功。想要完全匹配,可以在表达式末尾加上边界匹配符'$'。
      示例参见2.1小节。
  search(string[, pos[, endpos]]) | re.search(pattern, string[, flags]):
  这个方法用于查找字符串中可以匹配成功的子串。从string的pos下标处起尝试匹配pattern,如果pattern结束时仍可匹配,则返回一个Match对象;若无法匹配,则将pos加1后重新尝试匹配;直到pos=endpos时仍无法匹配则返回None。
  pos和endpos的默认值分别为0和len(string));re.search()无法指定这两个参数,参数flags用于编译pattern时指定匹配模式。

  •   # encoding: UTF-8
      1. import re
      2.
      3. # 将正则表达式编译成Pattern对象
      4. pattern = re.compile(r'world')
      5.
      6. # 使用search()查找匹配的子串,不存在能匹配的子串时将返回None
      7. # 这个例子中使用match()无法成功匹配
      8. match = pattern.search('hello world!')
      9.
      10. if match:
      11.     # 使用Match获得分组信息
      12.     print match.group()
      13.
      14. ### 输出 ###
      15. # world
  split(string[, maxsplit]) | re.split(pattern, string[, maxsplit]):
  按照能够匹配的子串将string分割后返回列表。maxsplit用于指定最大分割次数,不指定将全部分割。

  •   import re
      1.
      2. p = re.compile(r'\d+')
      3. print p.split('one1two2three3four4')
      4.
      5. ### output ###
      6. # ['one', 'two', 'three', 'four', '']
  findall(string[, pos[, endpos]]) | re.findall(pattern, string[, flags]):
  搜索string,以列表形式返回全部能匹配的子串。

  •   1. import re
      2.
      3. p = re.compile(r'\d+')
      4. print p.findall('one1two2three3four4')
      5.
      6. ### output ###
      7. # ['1', '2', '3', '4'
  finditer(string[, pos[, endpos]]) | re.finditer(pattern, string[, flags]):
  搜索string,返回一个顺序访问每一个匹配结果(Match对象)的迭代器。
  import re
  p = re.compile(r'\d+')
  for m in p.finditer('one1two2three3four4'):
  print m.group(),
  ### output ###
  # 1 2 3 4
  sub(repl, string[, count]) | re.sub(pattern, repl, string[, count]):
  使用repl替换string中每一个匹配的子串后返回替换后的字符串。
  当repl是一个字符串时,可以使用\id或\g<id>、\g<name>引用分组,但不能使用编号0。
  当repl是一个方法时,这个方法应当只接受一个参数(Match对象),并返回一个字符串用于替换(返回的字符串中不能再引用分组)。
  count用于指定最多替换次数,不指定时全部替换。
  1.import re
  2. p = re.compile(r'(\w+) (\w+)')
  3. s = 'i say, hello world!'
  4.
  5. print p.sub(r'\2 \1', s)
  6.
  7. def func(m):
  8.     return m.group(1).title() + ' ' + m.group(2).title()
  9.
  10. print p.sub(func, s)
  11.
  12. ### output ###
  13. # say i, world hello!
  14. # I Say, Hello World!
  subn(repl, string[, count]) |re.sub(pattern, repl, string[, count]):
  返回 (sub(repl, string[, count]), 替换次数)。
  import re
  p = re.compile(r'(\w+) (\w+)')
  s = 'i say, hello world!'
  print p.subn(r'\2 \1', s)
  def func(m):
  return m.group(1).title() + ' ' + m.group(2).title()
  print p.subn(func, s)
  ### output ###
  # ('say i, world hello!', 2)
  # ('I Say, Hello World!', 2

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-547837-1-1.html 上篇帖子: python自学argparse模块 下篇帖子: python中类的方法
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表