基本语法
元字符是正则的基本积木:匹配任意字符、边界、位置。先记住最常用的 10 个。
核心元字符
- .:任意字符(换行除外)
- \d:数字 [0-9];\D 非数字
- \w:字母数字下划线;\W 反义
- \s:空白(空格/制表/换行);\S 非空白
- ^:行开头;$:行结尾
- \b:单词边界
- [ ]:字符集(任选一个)
代码示例
import re
text = "a1 b2 c3 _x"
print(re.findall(r"\d", text)) # ['1', '2', '3']
print(re.findall(r"\w", text)) # 字母数字下划线
print(re.findall(r"[abc]", text)) # ['a', 'b', 'c']
print(re.findall(r"[0-9]", text)) # 数字
# ^ 和 $
print(re.match(r"^a", text) is not None) # 以 a 开头
print(re.search(r"x$", text) is not None) # 以 x 结尾
# 字符集范围
print(re.findall(r"[a-c]", "apple banana")) # ['a', 'b', 'a', 'a', 'a']
📚 Python 语法速查
常用条目速查,完整版见对应教程章节。可复制代码到在线运行中测试。
| 写法 / 语法 | 作用 |
|---|---|
print("hello") | 输出到控制台 |
name = "张三" | 变量赋值(无需声明类型) |
if x > 0: ... | 条件判断(注意冒号和缩进) |
for i in range(10): ... | 循环(缩进是语法的一部分) |
while x < 10: ... | 条件循环 |
def fn(a, b): return a + b | 定义函数 |
class Person: ... | 定义类 |
list = [1, 2, 3] | 列表(可改) |
tuple = (1, 2) | 元组(不可改) |
dict = {"key": "value"} | 字典(键值对) |
set = {1, 2, 3} | 集合(去重) |
len(obj) | 取长度 |
str(x) / int(x) / float(x) | 类型转换 |
s.split(",") | 字符串按分隔符拆分 |
" ".join(list) | 列表拼接成字符串 |
import os | 导入模块 |
from math import sqrt | 从模块导入指定函数 |
try: ... except Exception as e: ... | 异常捕获 |
with open("a.txt", "r") as f: ... | 文件读取(自动关闭) |
f"你好 {name}" | f-string 格式化 |
lambda x: x * 2 | 匿名函数 |
list(map(fn, arr)) | 函数式处理列表 |
range(start, stop, step) | 生成数字序列 |
if __name__ == "__main__": | 主入口判断 |
pip install 包名 | 安装第三方包(命令行) |