正则表达式 (regex) 是操作和分析文本的强大工具。在 Python 中,我们使用该re模块来处理正则表达式。
import re # No need to pip install its in the standard library
基础
基本特征
a: 完全符合。re.search(‘a’, ‘apple’)
.:匹配任何字符(换行符除外)。re.search(‘.’, ‘apple’)
\d:匹配任意数字(0-9)。re.search(‘\d’, ‘apple2’)
\D:匹配任何非数字。re.search(‘\D’, ‘1234a’)
\s: 匹配任何空格。re.search(‘\s’, ‘apple pie’)
\S:匹配任何非空白字符。re.search(‘\S’, ’ apple’)
\w:匹配任何字母数字字符和下划线(az、AZ、0-9、_)。re.search(‘\w’, ‘@apple!’)
\W:匹配任何非字母数字字符。re.search(‘\W’, ‘apple@’)
特殊字符
\t: 标签。re.search(‘\t’, ‘apple\t’)
\n: 新队。re.search(‘\n’, ‘apple\npie’)
\r:回车。re.search(‘\r’, ‘apple\r\n’)
\: 反斜杠。re.search(‘\\’, ‘apple\’