在编写处理网页文本的程序时,经常会有查找符合某些复杂规则的字符串的需要,正则表达式就是描述这些规则的工具。
基本语法和使用
1.常用元字符
| 元字符 | 含义 |
|---|---|
| . | 匹配除换行符以外的任意字符 |
| \b | 匹配单词的开始或结束 |
| \d | 匹配数字 |
| \w | 匹配字母、数字、下划线或汉字 |
| \s | 匹配任意空白符,包括空格、制表符、换行符、中文全角空格等 |
| ^ | 匹配字符串的开始 |
| $ | 匹配字符串的结束 |
2.字符转义
使用’\’作为转义字符。
3.重复
| 限定符 | 含义 |
|---|---|
| * | 重复0次或更多次 |
| + | 重复1次或更多次 |
| ? | 重复0次或者1次 |
| {n} | 重复n次 |
| {n,} | 重复n次或更多次 |
| {n,m} | 重复n到m次 |
4.字符集合
- [0-9]与\d等价
- [a-z0-9A-Z]与\w等价
5.分支条件
例:电话号码中有一种是3位区号,8位本地号(010-11223344),另一种是4位区号,7位本地号(0321-1234567);这时需要用到分支条件:0\d{2}-\d{8} | 0\d{3}-\d{7} 从左到右依次匹配,前面的条件满足了就不看后面的了,条件之间是一种或的关系。
6.分组
例:匹配192.168.1.1这样的IP地址。
((\d{1,3})\.){3}\d{1,3}。但是这样有可能出现333.444.555.666这样的IP地址所以是不合理的。
以下才是合理的表示方式。
((25[0-5] | 2[0-4]\d[0-1]\d{2} | [1-9]?\d)\.){3}((25[0-5] | 2[0-4]\d[0-1]\d{2} | [1-9]?\d)\.)
7.反义
| 代码 | 含义 |
|---|---|
| \W | 匹配任意不是字母、数字、下划线、汉字的字符 |
| \S | 匹配任意不是空白符的字符 |
| \D | 匹配任意非数字的字符 |
| \B | 匹配不是单词开头或结束的位置 |
| [^a] | 匹配除了a以外的任意字符 |
| [^abcde] | 匹配除了a、b、c、d、e这几个字母以外的任意字符 |
| [^(123 !abc)] | 匹配除了a、b、c和1、2、3这几个字符以外的任意字符 |
8.后向引用
9.零宽断言
10.注释
(?#comment)
例如:\b\w+(?#字符串)\b
11.贪婪与懒惰
12.处理选项
python与正则
1.re.match(pattern,string[,flags])
代码:
import re
# 将正则表达式编译成pattern对象
pattern = re.compile(r'\d+')
# 使用re.match匹配文本,获得匹配结果,无法匹配时将返回None
result1 = re.match(pattern,'192abc')
if result1:
print(result1.group())
else:
print('匹配失败1')
result2 = re.match(pattern,'abc192')
print(result2)
if result2:
print(result2.group())
else:
print('匹配失败2')
运行结果:
192
None
匹配失败2
2.re.search(pattern,string[,flags])
代码:
import re
# 将正则表达式编译成pattern对象
pattern = re.compile(r'dogs')
# 使用re.match匹配文本,获得匹配结果,无法匹配时将返回None
result1 = re.match(pattern,'Cats are smarter than dogs')
if result1:
print(result1.group())
else:
print('匹配失败1')
# 使用re.search匹配文本,获得匹配结果,无法匹配时将返回None
result2 = re.search(pattern,'Cats are smarter than dogs')
if result2:
print(result2.group())
else:
print('匹配失败2')
运行结果:
匹配失败1
dogs
3.re.findall(pattern,string[,flags])
代码:
import re
pattern = re.compile(r'\d+')
print(re.findall(pattern,'A1B2C3D4'))
运行结果:
[‘1’, ‘2’, ‘3’, ‘4’]
4.re.finditer(pattern,string[,flags])
代码:
import re
pattern = re.compile(r'\d+')
matchiter = re.finditer(pattern,'A1B2C3D4')
for match in matchiter:
print(match.group())
运行结果:
1
2
3
4
5.re.sub(patter,repl,string[,count])
代码:
import re
pattern = re.compile(r'(?P<word1>\w+) (?P<word2>\w+)') # 使用名称引用
s = 'i say,hello world!'
print(pattern.sub(r'\g<word2> \g<word1>',s))
pattern = re.compile(r'(\w+) (\w+)')
print(pattern.sub(r'\2 \1',s)) # 使用编号
def func(m):
return m.group(1).title()+' '+m.group(2).title()
print(pattern.sub(func,s))
运行结果:
say i,world hello!
say i,world hello!
I Say,Hello World!
6.re.subn(pattern,repl,string[,count])
代码:
import re
s = 'i say,hello world!'
pattern = re.compile(r'(\w+) (\w+)')
print(pattern.subn(r'\2 \1',s))
def func(m):
return m.group(1).title()+' '+m.group(2).title()
print(pattern.subn(func,s))
运行结果:
(‘say i,world hello!’, 2)
(‘I Say,Hello World!’, 2)
7.re.split(pattern,string[,maxsplit])
代码:
import re
pattern = re.compile(r'\d+')
print(re.split(pattern,'A1B2C3D4'))
运行结果:
[‘A’, ‘B’, ‘C’, ‘D’, ‘’]
Match对象的属性和方法
代码:
import re
pattern = re.compile(r'(\w+) (\w+) (?P<word>.*)')
match = pattern.match('I love you!')
print("match.string:",match.string)
print("match.re:",match.re)
print("match.pos:",match.pos)
print("match.endpos:",match.endpos)
print("match.lastindex:",match.lastindex)
print("match.lastgroup:",match.lastgroup)
print("match.group(1,2):",match.group(1,2))
print("match.groups():",match.groups())
print("match.groupdict():",match.groupdict())
print("match.start(2):",match.start(2))
print("match.end(2):",match.end(2))
print("match.span(2):",match.span(2))
print("match.expand(r'\\2 \\1 \\3'):",match.expand(r'\2 \1 \3'))
运行结果:
match.string: I love you!
match.re: re.compile(‘(\w+) (\w+) (?P<word style="box-sizing: border-box;">.*)’)
match.pos: 0
match.endpos: 11
match.lastindex: 3
match.lastgroup: word
match.group(1,2): (‘I’, ‘love’)
match.groups(): (‘I’, ‘love’, ‘you!’)
match.groupdict(): {‘word’: ‘you!’}
match.start(2): 2
match.end(2): 6
match.span(2): (2, 6)
match.expand(r’\2 \1 \3’): love I you!</word>
