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

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

相关推荐
数据智能老司机3 小时前
精通 Python 设计模式——创建型设计模式
python·设计模式·架构
数据智能老司机4 小时前
精通 Python 设计模式——SOLID 原则
python·设计模式·架构
c8i6 小时前
django中的FBV 和 CBV
python·django
c8i6 小时前
python中的闭包和装饰器
python
这里有鱼汤9 小时前
小白必看:QMT里的miniQMT入门教程
后端·python
TF男孩19 小时前
ARQ:一款低成本的消息队列,实现每秒万级吞吐
后端·python·消息队列
该用户已不存在1 天前
Mojo vs Python vs Rust: 2025年搞AI,该学哪个?
后端·python·rust
站大爷IP1 天前
Java调用Python的5种实用方案:从简单到进阶的全场景解析
python
用户8356290780511 天前
从手动编辑到代码生成:Python 助你高效创建 Word 文档
后端·python
_落纸1 天前
三大基础无源电子元件——电阻(R)、电感(L)、电容(C)
笔记