python规则表达式re模块:笔记0529

Python语言使用printf printf:https://blog.51cto.com/u_16099181/7758801

使用python进行自动化运维脚本编写时经常需要处理远程设备返回到控制字符,比如下面这个例子,控制字符在使用print进行调试输出时因为是非ascii字符不显示,但却是实际存在的。调试时容易忽略,总是很困惑无法对远程设备返回的字符串进行精确匹配。

>>> test="\x1b[?2004hroot"

>>> print(test)
root

>>> alist=[test, "control string"]

>>> print(alist)

'\\x1b\[?2004hroot', 'control string'

>>> prompt=re.sub(r"\x1b\[\?2004h","", test)

>>> alist=[prompt,"control string"]

>>> print(alist)

'root', 'control string'

>>> prompt=re.sub("\\x1b\[\?2004h","", test)

>>> alist=[prompt,"control string"]

>>> print(alist)

'root', 'control string'

>>> prompt=re.sub("\\x1b\[\?2004hro","", test)

>>> print(alist)

'root', 'control string'

>>> alist=[prompt,"control string"]

>>> print(alist)

'ot', 'control string'

>>>

r字符串前缀的作用是消除转义字符的特殊含义,使字符串中的每个字符都按照字面意义进行解释。这在处理包含大量反斜杠、制表符、换行符等特殊字符的字符串时非常有用。

r字符串前缀将反斜杠字符视为普通字符,而不是转义字符。这样可以避免由于转义字符造成的错误或混淆。

字符串前缀r" "的区别:

>>> print([re.sub(r"\\x1b\[\?2004hro","", test), 'control string'])

'\\x1b\[?2004hroot', 'control string'

>>> print([re.sub("\\x1b\[\?2004hro","", test), 'control string'])

'ot', 'control string'

>>> print([re.sub(r"\x1b\[\?2004hro","", test), 'control string'])

'ot', 'control string'

>>>

在正则表达式中,某些字符具有特殊含义,例如点号(.)、星号(*)、加号(+)等。如果要匹配这些特殊字符本身,而不是它们的特殊含义,可以使用r字符串前缀

>>> print([re.sub(r"\x1b[?2004hro","", test), 'control string']) #出错,特殊字符[必须成对出现

>>> print([re.sub(r"\x1b\[?2004hro","", test), 'control string']) #匹配失败

'\\x1b\[?2004hroot', 'control string'

>>> print([re.sub(r"\x1b\[\?2004hro","", test), 'control string'])

'ot', 'control string'

>>> print([re.sub(r"\x1b\[?2004hro","", test), 'control string']) #匹配失败,原字符?代表任何单一字符,在r字符串里面代表实际的普通字符?,这是模式字符串不是控制字符串而是一个实际的字符?,显然无法匹配上原始控制字符串。

'\\x1b\[?2004hroot', 'control string'

>>> print([re.sub("\x1b\[\?2004hro","", test), 'control string'])

'ot', 'control string'

>>> print([re.sub(r"\x1b\[\?2004hro","", test), 'control string'])

'ot', 'control string'

上面的例子中\x作为转义字符表示16进制,\[\?是将规则表达式中的特殊字符[和?作为普通字符处理。使用r字符串前缀时必须仍然加上\字符进行转义。与是否使用r前缀没有区别。

这里的\x1b\[\?和下面几个规则表达式的原字符有很大区别:点号(.)、星号(*)、加号(+)

>>> pattern = r'[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+'

>>> print(re.sub(pattern, '', email))

This is the email address: <<<

相同的是原字符点号(.)作为一个字符进行匹配时同样使用了\.

相关推荐
weelinking1 天前
【2026】08_Claude与版本控制:Git协作技巧
数据库·人工智能·git·python·数据挖掘·交互·cloudera
凉、介1 天前
Armv8-A virtualization 笔记 (二)
笔记·学习·嵌入式·arm·gic
智者知已应修善业1 天前
【ICL8038芯片正弦波三角波方波发生器电路】2024-1-5
驱动开发·经验分享·笔记·硬件架构·硬件工程
scan7241 天前
智能体多个工具调用
python
2401_867623981 天前
CSS Flex布局中如何设置子元素间距_掌握gap属性的现代用法
jvm·数据库·python
探序基因1 天前
身高与基因的关系
笔记
即使再小的船也能远航1 天前
【Python】安装
开发语言·python
weixin_421725261 天前
Linux 编程语言全解析:C、C++、Python、Go、Rust 谁更强?
linux·python·go·c·编程语言
没有梦想的咸鱼185-1037-16631 天前
AI-Python机器学习、深度学习核心技术与前沿应用及OpenClaw、Hermes自动化编程
人工智能·python·深度学习·机器学习·chatgpt·数据挖掘·数据分析
axinawang1 天前
第3课:变量与输入
python