1. 定义
正则表达式是一个特殊的字符序列,能方便的检查一个字符串是否与某种模式匹配。re模块使得python拥有全部的正则表达式功能。
2. 用途
通过使用正则表达式,可以:
测试字符串内的模式。—— 例如,可以测试输入字符串,以查看字符串内是否出现电话号码模式或信用卡号码模式。这称为数据验证。
替换文本。—— 可以使用正则表达式来识别文档中的特定文本,完全删除该文本或者用其他文本替换它。
基于模式匹配从字符串中提取子字符串。—— 可以查找文档内或输入域内特定的文本。
3. 语法

含义 | |
---|---|
'.' | 匹配所有字符串,除\n以外 |
'-' | 表示范围[0-9] |
'*' | 匹配前面的子表达式零次或多次。要匹配 * 字符,请使用 *。 |
'+' | 匹配前面的子表达式一次或多次。要匹配 + 字符,请使用 + |
'^' | 匹配字符串开头 |
'$' | 匹配字符串结尾 re |
'\' | 转义字符, 使后一个字符改变原来的意思,如果字符串中有字符*需要匹配,可以*或者字符集[*] re.findall(r'3*','3*ds')结['3*'] |
'*' | 匹配前面的字符0次或多次 re.findall("ab*","cabc3abcbbac")结果:['ab', 'ab', 'a'] |
'?' | 匹配前一个字符串0次或1次 re.findall('ab?','abcabcabcadf')结果['ab', 'ab', 'ab', 'a'] |
'{m}' | 匹配前一个字符m次 re.findall('cb{1}','bchbchcbfbcbb')结果['cb', 'cb'] |
'{n,m}' | 匹配前一个字符n到m次 re.findall('cb{2,3}','bchbchcbfbcbb')结果['cbb'] |
'\d' | 匹配数字,等于[0-9] re.findall('\d','电话:10086')结果['1', '0', '0', '8', '6'] |
'\D' | 匹配非数字,等于[^0-9] re.findall('\D','电话:10086')结果['电', '话', ':'] |
'\w' | 匹配字母和数字,等于[A-Za-z0-9] re.findall('\w','alex123,./;;;')结果['a', 'l', 'e', 'x', '1', '2', '3'] |
'\W' | 匹配非英文字母和数字,等于[^A-Za-z0-9] re.findall('\W','alex123,./;;;')结果[',', '.', '/', ';', ';', ';'] |
'\s' | 匹配空白字符 re.findall('\s','3*ds \t\n')结果[' ', '\t', '\n'] |
'\S' | 匹配非空白字符 re.findall('\s','3*ds \t\n')结果['3', '*', 'd', 's'] |
'\A' | 匹配字符串开头 |
'\Z' | 匹配字符串结尾 |
'\b' | 匹配单词的词首和词尾,单词被定义为一个字母数字序列,因此词尾是用空白符或非字母数字符来表示的 |
'\B' | 与\b相反,只在当前位置不在单词边界时匹配 |
[] | 是定义匹配的字符范围。比如 [a-zA-Z0-9] 表示相应位置的字符要匹配英文字符和数字。[\s*]表示空格或者*号 |
'(?P<name>...)' | 分组,除了原有编号外在指定一个额外的别名 |
例子
re.search("(?P<province>[0-9]{4})(?P<city>[0-9]{2})(?P<birthday>[0-9]{8})","371481199306143242").groupdict("city")
结果{'province': '3714', 'city': '81', 'birthday': '19930614'}
4. 使用
先compile,将pattern储存下来,再匹配(这样pattern可以重复使用)
compile
将pattern储存下来,以后可以调用
import re
pattern = re.compile('\$\d*\.\d{2}')
match()
进行匹配,返回一个bool值
result = pattern.match('$17.89')
print(result)
findall()
查找字符。从字符串中找出符合模式的字符序列:findall(模式(正则表达式),目标字符串), 返回值为list类型,list元素为匹配出的各个字符串
# Import the regular expression module
import re
# Find the numeric values: matches
# \d is the pattern required to find digits. This should be followed with a + so that the previous element is matched one or more times. This ensures that 10 is viewed as one number and not as 1 and 0.
matches = re.findall('\d+', 'the recipe calls for 10 strawberries and 1 banana')
# Print the matches
print(matches)
输出
[ '10', '1' ]
网友评论