常见的正则符号(Python 例子)
·
1. 定位符号
import re
print(re.findall(r'^Hello', 'Hello World')) # ['Hello'] ^ 匹配开头
print(re.findall(r'World$', 'Hello World')) # ['World'] $ 匹配结尾
print(re.findall(r'.', 'Hi')) # ['H','i'] . 匹配任意字符
2. 字符类
print(re.findall(r'[amk]', 'apple monkey kiwi')) # ['a','m','k'] 匹配 a 或 m 或 k
print(re.findall(r'[^abc]', 'abcxyz')) # ['x','y','z'] 匹配非 a/b/c
3. 数量限定符
print(re.findall(r'ab*', 'a ab abb abbb')) # ['a','ab','abb','abbb'] * 0次或多次
print(re.findall(r'ab+', 'a ab abb abbb')) # ['ab','abb','abbb'] + 1次或多次
print(re.findall(r'ab?', 'a ab abb abbb')) # ['a','ab','ab','ab'] ? 0或1次
print(re.findall(r'o{2}', 'Bob food')) # ['oo'] 精确2次
print(re.findall(r'o{2,}', 'foooood')) # ['oooo'] 至少2次
print(re.findall(r'o{1,3}', 'foooood')) # ['ooo'] 1到3次
4. 或者与分组
print(re.findall(r'cat|dog', 'I love cat and dog')) # ['cat','dog']
m = re.match(r'(ab)+c', 'abababc')
print(m.group()) # 'abababc' 捕获分组
5. 标志位
print(re.findall(r'(?i)python', 'PYTHON python PyThOn'))
# ['PYTHON', 'python', 'PyThOn'] i=忽略大小写
6. 非捕获分组
print(re.findall(r'(?:ab)+', 'abababc')) # ['ababab'] 不保存分组内容
7. 注释
print(re.findall(r'foo(?# this is comment)bar', 'foobar')) # ['foobar']
8. 前瞻与回溯
# 前向肯定 (?=re)
print(re.findall(r'foo(?=bar)', 'foobar foo123')) # ['foo'] foo 后必须跟 bar
# 前向否定 (?!re)
print(re.findall(r'foo(?!bar)', 'foobar foo123 foo')) # ['foo','foo'] foo 后不能跟 bar
# 回顾肯定 (?<=re)
print(re.findall(r'(?<=\$)\d+', 'Price is $100 and $20')) # ['100','20'] 前面要有 $
# 回顾否定 (?<!re)
print(re.findall(r'(?<!\$)\d+', 'Price is $100 and 200')) # ['200'] 前面不能有 $
9. 单词边界
print(re.findall(r'er\b', 'never verb')) # ['er'] 单词边界
print(re.findall(r'er\B', 'never verb')) # ['er'] 非单词边界
10. 特殊字符类
print(re.findall(r'\w', 'Hi_123!')) # ['H','i','_','1','2','3'] 字母数字下划线
print(re.findall(r'\W', 'Hi_123!')) # ['!'] 非字母数字下划线
print(re.findall(r'\s', 'a b\tc\n')) # [' ','\t','\n'] 空白符
print(re.findall(r'\S', 'a b')) # ['a','b'] 非空白符
print(re.findall(r'\d', 'a1b2')) # ['1','2'] 数字
print(re.findall(r'\D', 'a1b2')) # ['a','b'] 非数字
11. 字符串边界
print(re.findall(r'\AHello', 'Hello World')) # ['Hello'] 只能匹配开头
print(re.findall(r'World\Z', 'Hello World')) # ['World'] 结尾(不含换行)
12. 分组引用
m = re.match(r'(\w+) \1', 'hello hello')
print(m.group()) # 'hello hello' \1 表示第1个分组的内容
更多推荐

所有评论(0)