Python正则表达式中的字符类或字符集有什么用途?
阅读更多:Python 教程
什么是字符类?
在 Python 中,字符类或字符集是由一组字符构成的正则表达式,它表示一个字符可以属于这个集合中的任意一个字符。比如 [abcd] 表示一个字符可以是 a、b、c 或者 d 中的任意一个。字符集可以匹配与集合中任意一个字符相匹配的一个字符。
如何使用字符集?
在 Python 中使用字符集,在正则表达式中包含一对方括号,方括号内部用逗号隔开的方式指定匹配的字符集。下面是一些使用字符集的示例代码:
import re
# 匹配可算的数字 0-9
pattern = r"[0-9]"
print(re.findall(pattern, "1a2b3c4d5e"))
# 匹配小写字母 a-z 和大写字母 A-Z
pattern = r"[a-zA-Z]"
print(re.findall(pattern, "aBcDeFgHiJ1k2l3m4n5o6p"))
# 匹配以大写字母开头的单词
pattern = r"[A-Z]\w*"
print(re.findall(pattern, "Apple is a tech company, not a fruit."))
# 匹配非数字的字符
pattern = r"[^\d]"
print(re.findall(pattern, "1a2b3c4d5e"))
# 匹配既不是数字也不是字母的字符
pattern = r"[^\w]"
print(re.findall(pattern, "The dog jumped over the fence, but the cat stayed on the ground."))
什么时候使用字符集?
字符集可以帮助我们限制正则表达式匹配的范围,让我们更加灵活地匹配所需的字符。下面是一些常见的情况,需要使用字符集:
- 匹配单词的首字母为大写
- 匹配手机号码
- 匹配 IP 地址
- 匹配邮箱地址
内置的字符类
Python 中还提供了内置的字符类,用于匹配特定类型的字符。例如,\d 用于匹配数字字符,[0-9] 也可以达到相同的效果。下表列出了 Python 中的内置字符类及用途:
| 字符类 | 用途 |
|---|---|
\d |
匹配数字 |
\D |
匹配非数字 |
\w |
匹配字母、数字及下划线 |
\W |
匹配非字母、数字及下划线 |
\s |
匹配空白字符,包括空格、制表符、换行符等 |
\S |
匹配非空白字符 |
下面是一些使用内置字符类的示例代码:
import re
# 匹配电话号码形式的字符串
pattern = r"\d{3}-\d{8}|\d{4}-\d{7}"
print(re.findall(pattern, "011-12345678, 021-123456789"))
# 匹配 IP 地址形式的字符串
pattern = r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}"
print(re.findall(pattern, "192.168.0.1 is a private IP address."))
# 匹配邮箱地址
pattern = r"\w+@\w+\.com"
print(re.findall(pattern, "My email is example@example.com."))
预定义的字符集
在 Python 中,还提供了一些预定义的字符集,可以用于匹配特定类型的字符。这些预定义的字符集以反斜杠开头,例如 \b 代表单词边界,\t 代表制表符,\n 代表换行符等。下表列出了 Python 中的常用的预定义字符集及用途:
| 字符集 | 用途 |
|---|---|
\b |
匹配单词边界 |
\t |
匹配制表符 |
\n |
匹配换行符 |
\r |
匹配回车符 |
\f |
匹配分页符 |
\v |
匹配垂直制表符 |
\d |
匹配数字字符 |
\D |
匹配非数字字符 |
\w |
匹配字母、数字及下划线 |
\W |
匹配非字母、数字及下划线 |
\s |
匹配空白字符,包括空格、制表符、换行符等 |
\S |
匹配非空白字符 |
下面是一些使用预定义字符集的示例代码:
import re
# 匹配单词边界
pattern = r"\bboy\b"
print(re.findall(pattern, "This is a boy. That is a toy."))
# 匹配制表符
pattern = r"\t"
print(re.findall(pattern, "This is a \t tab."))
# 匹配换行符
pattern = r"\n"
print(re.findall(pattern, "This is a \n new line."))
# 匹配数字字符
pattern = r"\d+"
print(re.findall(pattern, "I have 3 apples, 5 bananas and 1 peach."))
# 匹配非字母、数字及下划线
pattern = r"[^\w]"
print(re.findall(pattern, "The dog jumped over the fence, but the cat stayed on the ground."))
排除字符集
有时候,在一个字符集中,我们需要匹配除了某些字符以外的所有字符,这个时候可以使用排除字符集。排除字符集是在方括号内加入 ^ 符号,代表除了这个字符集中的字符以外的其他所有字符。下面是一个排除字符集的示例代码:
import re
# 匹配非数字的字符
pattern = r"[^\d]"
print(re.findall(pattern, "1a2b3c4d5e"))
# 匹配既不是数字也不是字母的字符
pattern = r"[^\w]"
print(re.findall(pattern, "The dog jumped over the fence, but the cat stayed on the ground."))
总结
Python 中的字符类或字符集是一个非常有用的工具,可以帮助我们更灵活地匹配所需的字符。我们可以通过方括号内逗号隔开的方式定义一个自己的字符集,也可以使用 Python 中的内置字符类和预定义字符集来匹配特定类型的字符。在匹配一些特定类型的字符时,字符集会是一个很好的选择。
极客笔记