Python中正则表达式re模块-compile()和findall()

时间:2022-06-01 19:32:44

正则表达式中字符含义:

预定义字符集
\d 数字:[0-9]
\D 非数字:[^\d]
\s 空白字符:[\t\f\r\v\n]
\S 非空白字符:[^\s]
\w 单词字符:[A-Za-z0-9_]
\D 非单词字符:[^\w]
数量词(用在字符或者(…)之后)
* 匹配前一个字符0次或者无限次
+ 匹配前一个字符1次或者无限次
匹配前一个字符0次或者1次
{m} 匹配前一个字符m次
{m,n} 匹配前一个字符m次至n次,如果m省略,即0~n次,如果n省略,即m~无限次

使用正则表达式来匹配字符:
匹配单个字符:

当正则表达式中不带括号时,列表的元素为字符串,此字符串为整个正则表达式匹配的内容

import re
str="this is an example"
re1=re.compile('\w')
re1.findall(str)
['t', 'h', 'i', 's', 'i', 's', 'a', 'n', 'e', 'x', 'a', 'm', 'p', 'l', 'e']

匹配单词:

re1=re.compile('\w+')     #不带空格
re1.findall(str)
['this', 'is', 'an', 'example']
re1=re.compile('\w+\s')       #带有空格
re1.findall(str)
['this ', 'is ', 'an ']
re1=re.compile('\w+\s+\w+')   #字符空格字符
re1.findall(str)
['this is', 'an example']

当正则表达式中带有一个括号时,列表的元素为字符串,次字符串的内容与括号中的正则表达式相对应(不是整个表达式的匹配内容)

re1=re.compile('(\w+)\s+\w+')
re1.findall(str)
['this', 'an']

当正则表达式中带有多个括号时,列表的元素为多个字符串组成的tuple,tuple中的字符串个数与括号对数相同,字符串内容与每个括号内的正则表达式相对应,并且排放顺序是按括号出现的顺序。

 re1=re.compile('((\w+)\s+\w+)')
 re1.findall(str)
[('this is', 'this'), ('an example', 'an')]

参考博客:http://blog.csdn.net/drdairen/article/details/51134816[感谢博主]