加入收藏 | 设为首页 | 会员中心 | 我要投稿 PHP编程网 - 金华站长网 (https://www.0579zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Python正则表达式操作指南

发布时间:2016-11-28 10:12:00 所属栏目:大数据 来源:网络整理
导读:Python 自1.5版本起增加了re 模块,它提供 Perl 风格的正则表达式模式。Python 1.5之前版本则是通过 regex 模块提供 Emacs 风格的模式。Emacs 风格模式可读性稍差些,而且功能也不强,因此编写新代码时尽量不要再使用 regex 模块,当然偶尔你还是可能在老

这个方法用于查找字符串中可以匹配成功的子串。从string的pos下标处起尝试匹配pattern,如果pattern结束时仍可匹配,则返回一个Match对象;若无法匹配,则将pos加1后重新尝试匹配;直到pos=endpos时仍无法匹配则返回None。

pos和endpos的默认值分别为0和len(string));re.search()无法指定这两个参数,参数flags用于编译pattern时指定匹配模式。

# encoding: UTF-8 
import re 
 # 将正则表达式编译成Pattern对象 

pattern = re.compile(r'world') 
 
# 使用search()查找匹配的子串,不存在能匹配的子串时将返回None 
# 这个例子中使用match()无法成功匹配 

match = pattern.search('hello world!') 
if match: 
  # 使用Match获得分组信息 
  print match.group() 
### 输出 ### 
# world
split(string[, maxsplit]) | re.split(pattern, string[, maxsplit]):

按照能够匹配的子串将string分割后返回列表。maxsplit用于指定最大分割次数,不指定将全部分割。

import re
p = re.compile(r'd+')
print p.split('one1two2three3four4')
### output ###
# ['one', 'two', 'three', 'four', '']
findall(string[, pos[, endpos]]) | re.findall(pattern, string[, flags]): 

搜索string,以列表形式返回全部能匹配的子串。

import re
p = re.compile(r'd+')
print p.findall('one1two2three3four4')
### output ###
# ['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或glt;idgt;、glt;namegt;引用分组,但不能使用编号0。
当repl是一个方法时,这个方法应当只接受一个参数(Match对象),并返回一个字符串用于替换(返回的字符串中不能再引用分组)。

count用于指定最多替换次数,不指定时全部替换。

import re
p = re.compile(r'(w+) (w+)')
s = 'i say, hello world!'
print p.sub(r'2 1', s)
def func(m):
  return m.group(1).title() + ' ' + m.group(2).title()
print p.sub(func, s)
### output ###
# say i, world hello!
# 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)

以上就是Python对于正则表达式的支持。熟练掌握正则表达式是每一个程序员必须具备的技能,这年头没有不与字符串打交道的程序了。笔者也处于初级阶段,与君共勉,^_^

另外,图中的特殊构造部分没有举出例子,用到这些的正则表达式是具有一定难度的。有兴趣可以思考一下,如何匹配不是以abc开头的单词,^_^

(编辑:PHP编程网 - 金华站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!