正则表达式元字符教程
·
正则表达式 教程
掌握7个核心元字符的使用方法
通配符
字符集
重复元字符
^和$
转义符
分组与提取
|或操作
- 通配符 (.)
. 通配符、万能通配符或通配元字符,匹配1个除了换行符\n以外的任何字符。
import re
s = "apple ape agree age amaze animate advertise a\\ne "
r = re.findall("ape", s) # 匹配'ape'
r = re.findall("a.e", s) # 匹配a和e之间有一个任意字符
r = re.findall("a..e", s) # 匹配a和e之间有两个任意字符
r = re.findall("a...e", s) # 匹配a和e之间有三个任意字符
print(r)
- 字符集 ([])
[] 字符集,匹配一个中括号中出现的任意原子符号。
import re
s = "apple ape agree age amaze animate advertise a\\ne a&e a@e a6e a9e"
r = re.findall("a.e", s) # 匹配a和e之间有一个任意字符
r = re.findall("a[pgz]e", s) # 匹配a和e之间有p、g或z
r = re.findall("a[a-z]e", s) # 匹配a和e之间有一个小写字母
r = re.findall("a[^a-z]e", s) # 匹配a和e之间有一个非小写字母
r = re.findall("a[0-9]e", s) # 匹配a和e之间有一个数字
print(r)
- 重复元字符 ({}, *, +, ?)
重复相关的4个元字符: {}, *, +, ?
{n,m}: 数量范围贪婪符,指定左边原子的数量范围
*: 指定左边原子出现0次或多次,等同{0,}
+: 指定左边原子出现1次或多次,等同{1,}
?: 指定左边原子出现0次或1次,等同{0,1}
import re
s = "aeeee apple acre ape agree age amaze animate advertise a\\ne a&e a@e a6e a9e"
r = re.findall("a.{2}e", s) # 匹配a和e之间有2个任意字符
r = re.findall("a[a-z]{2}e", s) # 匹配a和e之间有2个小写字母
r = re.findall("a.{3}e", s) # 匹配a和e之间有3个任意字符
r = re.findall("a.{1,3}e", s) # 贪婪匹配,优先按最大3匹配
r = re.findall("a.{1,3}?e", s) # 非贪婪匹配,按最小1匹配
r = re.findall("a.{1,}?e", s) # 非贪婪匹配,按最小1匹配
print(r)
*: 0次或多次
+: 1次或多次
?: 0次或1次
r = re.findall("a.*e", s) # 贪婪匹配
r = re.findall("a.*?e", s) # 非贪婪匹配
r = re.findall("a[a-z]*?e", s) # 非贪婪匹配小写字母
print(r)
- ^和$
^匹配字符串开头,$匹配字符串结尾。
import re
s = "apple\nape\nagree\nage\namaze\nanimate\nadvertise"
r = re.findall("^a", s) # 匹配每行开头是a
r = re.findall("e$", s) # 匹配每行结尾是e
r = re.findall("^a.*e$", s, re.MULTILINE) # 匹配以a开头e结尾的行
print(r)
- 转义符 ()
\ 用于转义特殊字符,使其失去特殊含义。
import re
s = "apple$ ape* agree? age+ amaze^ animate\\ advertise."
r = re.findall("apple\\$", s) # 匹配apple$
r = re.findall("ape\\*", s) # 匹配ape*
r = re.findall("agree\\?", s) # 匹配agree?
r = re.findall("age\\+", s) # 匹配age+
r = re.findall("amaze\\^", s) # 匹配amaze^
r = re.findall("animate\\\\", s) # 匹配animate\
r = re.findall("advertise\\.", s) # 匹配advertise.
print(r)
- 分组与优先提取 (())
() 用于分组和优先提取匹配内容。
import re
s = "John: 30, Alice: 25, Bob: 35"
# 提取名字和年龄
r = re.findall("([A-Za-z]+): (\\d+)", s) # 返回元组列表
print(r) # [('John', '30'), ('Alice', '25'), ('Bob', '35')]
分组引用
s = "hello hello world world"
r = re.sub(r"(\\w+) \\1", r"\\1", s) # 去除连续重复单词
print(r) # "hello world"
- 或操作 (|)
| 用于匹配多个模式中的任意一个。
import re
s = "apple banana cherry date elderberry fig grape"
r = re.findall("apple|banana|cherry", s) # 匹配apple或banana或cherry
print(r) # ['apple', 'banana', 'cherry']
s = "123-456-7890 (123)456-7890 123.456.7890"
r = re.findall("\\(?\\d{3}\\)?[-.]\\d{3}[-.]\\d{4}", s) # 匹配多种电话号码格式
print(r)
更多推荐
所有评论(0)