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: <<<

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

相关推荐
刘某的Cloud17 小时前
列表、元组、字典、集合-组合数据类型
linux·开发语言·python
nnsix17 小时前
QFramework学习笔记
笔记·学习
XFF不秃头17 小时前
力扣刷题笔记-全排列
c++·笔记·算法·leetcode
ys~~17 小时前
git学习
git·vscode·python·深度学习·学习·nlp·github
Mqh18076217 小时前
day46 Grad-CAM
python
郝学胜-神的一滴17 小时前
Python魔法函数一览:解锁面向对象编程的奥秘
开发语言·python·程序人生
白露与泡影18 小时前
使用systemd,把服务装进 Linux 心脏里~
linux·运维·python
لا معنى له18 小时前
目标分割介绍及最新模型----学习笔记
人工智能·笔记·深度学习·学习·机器学习·计算机视觉
yaoh.wang18 小时前
力扣(LeetCode) 100: 相同的树 - 解法思路
python·程序人生·算法·leetcode·面试·职场和发展·跳槽
Sunsets_Red19 小时前
2025 FZYZ夏令营游记
java·c语言·c++·python·算法·c#