dongfangho 发表于 2018-8-8 09:32:14

Python标准库 - re

  编写代码时, 经常要匹配特定字符串, 或某个模式的字符串, 一般会借助字符串函数, 或正则表达式完成.
  对于正则表达式, 有些字符具有特殊含义, 需使用反斜杠字符'\'转义, 使其表示本身含义. 如想匹配字符'\', 却要写成'\\\\', 很是困扰. Python中Raw string解决了该问题, 只需给'\'加上前缀'r'即可, 如r'\n', 表示'\'和'n'两个普通字符, 而不是原来的换行. 前缀'r'类似于sed命令的-r(use extended regular expressions)参数.
  正则表达式可包括两部分, 一是正常字符, 表本身含义; 二是特殊字符, 表一类正常字符, 或字符数量...
  re模块提供了诸多方法进行正则匹配.
  match    Match a regular expression pattern to the beginning of a string.
  search   Search a string for the presence of a pattern.
  sub      Substitute occurrences of a pattern found in a string.
  subn   Same as sub, but also return the number of substitutions made.
  split    Split a string by the occurrences of a pattern.
  findallFind all occurrences of a pattern in a string.
  finditer Return an iterator yielding a match object for each match.
  purge    Clear the regular expression cache.
  escape   Backslash all non-alphanumerics in a string.
  还有compile函数, 其较特殊, 将匹配模式编译为一个正则表达式对象(RegexObject, _sre.SRE_Pattern), 并返回, 该对象仍然可以使用上述这些函数. 这也从侧面说明了, 对于re模块, 有非编译和编译两种使用方式, 如下所示.
  1.
  result = re.match(pattern, string)
  2.
  prog = re.compile(pattern)
  result = prog.match(string)
  它们达到的效果是相同的, 只是后者暂存了正则表达式对象, 对于某块代码中频繁使用该正则表达式的情形, 后者性能一般会高于前者.
  对于match()和search()匹配成功, 会返回一个匹配对象(Match Object, _sre.SRE_Match), 其也有若干方法, 下面几个较常用.
  group
  group() -> str or tuple.
  Return subgroup(s) of the match by indices or names.
  For 0 returns the entire match.
  groups(...)
  groups() -> tuple.
  Return a tuple containing all the subgroups of the match, from 1.
  The default argument is used for groups
  that did not participate in the match
  end(...)
  end() -> int.
  Return index of the end of the substring matched by group.
  start(...)
  start() -> int.
  Return index of the start of the substring matched by group.
  至此对re模块框架性梳理就这样了, 给出些例子, 对上面的内容总结下.
  1.
  In : text = "He was carefully disguised but captured quickly by police."
  In : re.findall(r"\w+ly", text)
  Out: ['carefully', 'quickly']
  2.
  In : m = re.match(r"(\w+) (\w+)", "Isaac Newton, physicist")
  In : m.group(0)
  Out: 'Isaac Newton'
  In : m.group(1)
  Out: 'Isaac'
  In : m.group(2)
  Out: 'Newton'
  In : m.group(1, 2)
  Out: ('Isaac', 'Newton')
  3.
  In : account = "abcxyz_"
  In : replace_regex = re.compile(r'_$')
  In : replace_regex.sub(account, account)
  Out: 'abcxyza'
  正则表达式使用中的细节还有很多, 这里无法尽数, 实践过程中慢慢体会和总结吧.
页: [1]
查看完整版本: Python标准库 - re