Home > Backend Development > Python Tutorial > 在Python中使用正则表达式的方法

在Python中使用正则表达式的方法

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-06-10 15:08:04
Original
1205 people have browsed it

正则表达式(regular expression)是一种用形式化语法描述的文本匹配模式。在需要处理大量文本处理的应用中有广泛的使用,我没使用的编辑器,IDE中的搜索常用正则表达式作为搜索模式。玩过*nix系统的都知道如sed,grep,awk这类的命令,他们是非常强大的文本处理工具。几乎所有的语言都有对正则表达式的支持,有的直接在语法中支持,有的使用扩展库的形式。python使用的就是扩展库re。

    re.search(pattern,string,flag=0)

    搜索文本中的匹配的模式是最常用的.以模式和文本作为输入,如果有匹配则返回一个Match对象,反之返回None。
    每个Match对象包括相关的匹配信息:原字符串、正则表达式和匹配的文本在字符串中的位置。
import re 
pattern = "this" 
text = "Does this text match the pattern?" 
match = re.search(pattern, text) # 返回一个Match对象 
print match.re.pattern # 要匹配的正则表达式"this"
print match.string   # 匹配的文本"Does this match the pattern?" 
print match.start()   # 匹配的开始位置 5
print match.end()    # 匹配的结束位置 9

Copy after login

re.compile(pattern,flag=0)
如果程序中频繁的使用到同一个正则表达式,每次使用的时候都写一遍正则表达式不仅不高效而且会大大增加出错的几率,re提供了compile函数将一个表达式字符串编译为一个RegexObject。
模块级函数会维护已编译表达式的一个缓存,而这个缓存是的大小是有限制的。直接使用已经编译的表达式可以避免缓存查找的开销,并且在加载模块时就会预编译所有的表达式。

import re 
regex = re.compile("this") 
text = "Does this text match the pattern?" 
match = regex.search(text) 
if match: 
  print "match" 
  match.group(0)  #返回匹配的字符串  
else:
  print "not match" 

Copy after login

re.findall(pattern, string, flag=0)
使用search会返回匹配的单个实例,使用findall会返回所有匹配的不重叠的子串。

import re 
pattern = 'ab' 
text = 'abbaaabbbbaaaaaa' 
re.findall(pattern, text)  # 返回['ab', 'ab'] 

Copy after login

re.finditer(pattern, string, flag=0)
finditer会返回一个迭代器,会生成Match实例,不像findall()返回字符串.

import re 
pattern = 'ab' 
text = 'abbaaabbbbaaaaaa' 
match = re.finditer(pattern, text)  
for m in match:
  print m.start() 
  print m.end()

Copy after login

以上的例子会分别输出两次匹配结果的起始位置和结束位置。

正则匹配默认采用的是贪婪算法,也就是说会re在匹配的时候会利用尽可能多的输入,而使用?可以关闭这种贪心行为,只匹配最少的输入。这之前先说下量词。

量词是为了简化正则表达式的读写而定义的,通用的形式是{m,n},这表示匹配的个数至少是m,最多是n,在','之后不能有空格,否则会出错,并且均为闭区间。

  • {n} 之前的元素必须出现n次
  • {m,n} 之前元素最少出现m次,最多n次
  • {m,} 之前的元素最少出现m次,无上限
  • {0,n} 之前的元素可以不出现,也可以出现,出现的话最多出现n次

除了之上,还有三个常用的量词*,?和+

  • * 等价于{0,}
  • + 等价于{1,}
  • \? 等价于{0,1}

还有^和$,分别表示段或者字符串的开始与结束。

import re 
re.search("^travell?er$", "traveler")  # True 
re.search("^travell?er$", "traveller")  # True  
re.search("^ab\*", "abbbbbbb")      # True,返回"abbbbbbb" 
re.search("^ab\*?", "abbbbbbb")     # True,返回"a" 
re.search("^ab+", "abbbbbbb")      # True,返回"abbbbbbb" 
re.search("^ab+?", "abbbbbbb")      # True,返回"ab" 

Copy after login

对于一些预定义的字符集可以使用转义码可以更加紧凑的表示,re可以识别的转义码有3对,6个,分别为三个字母的大小写,他们的意义是相反的。

  • \d : 一个数字
  • \D : 一个非数字
  • \w : 字母或者数字
  • \W : 非字母,非数字
  • \s : 空白符(制表符,空格,换行符等)
  • \S : 非空白符

如果想指定匹配的内容在文本的相对位置,可以使用锚定,跟转义码类似。

  • ^ 字符或行的开始
  • $ 字符或行的结束
  • \A 字符串的开始
  • \Z 字符串结束
  • \b 一个单词开头或者末尾的空串
  • \B 不在一个单词开头或末尾的空串
import re
the_str = "This is some text -- with punctuation" 
re.search(r'^\w+', the_str).group(0)    # This
re.search(r'\A\w+', the_str).group(0)   # This 
re.search(r'\w+\S*$', the_str).group(0)  # punctuation 
re.search(r'\w+\S*\Z', the_str).group(0)  # punctuation 
re.search(r'\w*t\W*', the_str).group(0)  # text -- 
re.search(r'\bt\w+', the_str).group(0)   # text 
re.search(r'\Bt*\B', the_str).group(0)   # 没有匹配 

Copy after login

用组来解析匹配,简单的说就是在一个正则表达式中有几个小括号()将匹配的表达式分成不同的组,使用group()函数来获取某个组的匹配,其中0为整个正则表达式所匹配的内容,后面从1开始从左往右依次获取每个组的匹配,即每个小括号中的匹配。使用groups()可以获取所有的匹配内容。

import re 
the_str = "--aabb123bbaa" 
pattern = r'(\W+)([a-z]+)(\d+)(\D+)' 
match = re.search(pattern, the_str)  
match.groups()  # ('--', 'aabb', '123', 'bbaa') 
match.group(0)  # '--aabb123bbaa' 
match.group(1)  # '--' 
match.group(2)  # 'aabb' 
match.group(3)  # '123' 
match.group(4)  # 'bbaa'

Copy after login

python对分组的语法做了扩展,我们可以对每个分组进行命名,这样便可以使用名称来调用。语法:(?Ppattern),使用groupdict()可以返回一个包含了组名的字典。

import re 
the_str = "--aabb123bbaa" 
pattern = r'(&#63;P<not_al_and_num>\W+)(&#63;P<al>[a-z]+)(&#63;P<num>\d+)(&#63;P<not_num>\D+)' 
match = re.search(pattern, the_str)  
match.groups()  # ('--', 'aabb', '123', 'bbaa') 
match.groupdict() # {'not_al_and_num': '--', 'not_num': 'bbaa', 'num': '123', 'al': 'aabb'} 
match.group(0)          # '--aabb123bbaa' 
match.group(1)          # '--' 
match.group(2)          # 'aabb' 
match.group(3)          # '123' 
match.group(4)          # 'bbaa'  
match.group('not_al_and_num')  # '--'
match.group('al')         # 'aabb' 
match.group('num')        # '123' '
match.group('not_num')      # 'bbaa'

Copy after login

以上的group()方法在使用的时候需要注意,只有在有匹配的时候才会正常运行,否则会抛错,所以在不能保证有匹配而又要输出匹配结果的时候,必须做校验。

在re中可以设置不通的标志,也就是search()和compile()等中都包含的缺省变量flag。使用标志可以进行完成一些特殊的要求,如忽略大小写,多行搜索等。

import re 
the_str = "this Text" 
re.findall(r'\bt\w+', the_str)  # ['this'] 
re.findall(r'\bt\w+', the_str, re.IGNORECASE) # ['this', 'Text'] 

Copy after login

 

Related labels:
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template