码迷,mamicode.com
首页 > 编程语言 > 详细

Python: 字符串搜索和匹配,re.compile() 编译正则表达式字符串,然后使用match() , findall() 或者finditer() 等方法

时间:2018-02-12 15:18:39      阅读:516      评论:0      收藏:0      [点我收藏+]

标签:nts   form   for   分组   方法   dig   sre   blog   one   

1. 使用find()方法

>>> text = ‘yeah, but no, but yeah, but no, but yeah‘

>>> text.find(‘no‘)
10

2. 使用re.match()

对于复杂的匹配需要使用正则表达式和re 模块。为了解释正则表达式的基本原理,假设想匹配数字格式的日期字符串比如11/27/2012 ,可以这样做:
>>> text1 = ‘11/27/2012‘
>>> text2 = ‘Nov 27, 2012‘
>>>
>>> import re
>>> # Simple matching: \d+ means match one or more digits
>>> if re.match(r‘\d+/\d+/\d+‘, text1):
... print(‘yes‘)
... else:
... print(‘no‘)
...
yes
>>> if re.match(r‘\d+/\d+/\d+‘, text2):
... print(‘yes‘)
... else:
... print(‘no‘)
...
no

3.将字符串预编译re.compile(),再match()

如果想使用同一个模式去做多次匹配,应该先将模式字符串预编译为模式对象。比如:
>>> datepat = re.compile(r‘\d+/\d+/\d+‘)
>>> if datepat.match(text1):
... print(‘yes‘)
... else:
... print(‘no‘)
...
yes
>>> if datepat.match(text2):

... print(‘yes‘)
... else:
... print(‘no‘)
...
no

4.使用findall()方法

match() 总是从字符串开始去匹配,如果你想查找字符串任意部分的模式出现位置,使用findall() 方法去代替。比如:
>>> text = ‘Today is 11/27/2012. PyCon starts 3/13/2013.‘
>>> datepat.findall(text)
[‘11/27/2012‘, ‘3/13/2013‘]

5. .group()方法去捕获分组


在定义正则式的时候,通常会利用括号去捕获分组。比如:
>>> datepat = re.compile(r‘(\d+)/(\d+)/(\d+)‘)
捕捕获分组可以使得后面的处理更加简单,因为可以分别将每个组的内容提取出来。
比如:
>>> m = datepat.match(‘11/27/2012‘)
>>> m
<_sre.SRE_Match object at 0x1005d2750>
>>> # Extract the contents of each group
>>> m.group(0)
‘11/27/2012‘
>>> m.group(1)
‘11‘
>>> m.group(2)
‘27‘
>>> m.group(3)
‘2012‘
>>> m.groups()
(‘11‘, ‘27‘, ‘2012‘)
>>> month, day, year = m.groups()

 >>> text
‘Today is 11/27/2012. PyCon starts 3/13/2013.‘
>>> datepat.findall(text)
[(‘11‘, ‘27‘, ‘2012‘), (‘3‘, ‘13‘, ‘2013‘)]
>>> for month, day, year in datepat.findall(text):
... print(‘{}-{}-{}‘.format(year, month, day))
...
2012-11-27
2013-3-13

6. 迭代方式返回finditer()

findall() 方法会搜索文本并以列表形式返回所有的匹配。如果你想以迭代方式返

>>> for m in datepat.finditer(text):
... print(m.groups())
...
(‘11‘, ‘27‘, ‘2012‘)
(‘3‘, ‘13‘, ‘2013‘)

核心步骤就是先使用re.compile() 编译正则表达式字符串,然后使用match() , findall() 或者finditer() 等方法。

7. 精确匹配

如果你想精确匹配,确保你的正则表达式以$ 结尾,就像这么这样:
>>> datepat = re.compile(r‘(\d+)/(\d+)/(\d+)$‘)
>>> datepat.match(‘11/27/2012abcdef‘)
>>> datepat.match(‘11/27/2012‘)
<_sre.SRE_Match object at 0x1005d2750>
>>>

8.简单的文本匹配/搜索

最后,如果你仅仅是做一次简单的文本匹配/搜索操作的话,可以略过编译部分,直接使用re 模块级别的函数。比如:
>>> re.findall(r‘(\d+)/(\d+)/(\d+)‘, text)
[(‘11‘, ‘27‘, ‘2012‘), (‘3‘, ‘13‘, ‘2013‘)]
>>>
但是需要注意的是,如果你打算做大量的匹配和搜索操作的话,最好先编译正则表达式,然后再重复使用它。模块级别的函数会将最近编译过的模式缓存起来,因此并会消耗太多的性能,但是如果使用预编译模式的话,将会减少查找和一些额外的处理损耗

 

Python: 字符串搜索和匹配,re.compile() 编译正则表达式字符串,然后使用match() , findall() 或者finditer() 等方法

标签:nts   form   for   分组   方法   dig   sre   blog   one   

原文地址:https://www.cnblogs.com/baxianhua/p/8444232.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!