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

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

相关推荐
闻道且行之9 小时前
TurboOCR:基于PP-OCRv6的极速Windows离线OCR工具,深度解析3.4GB依赖背后的技术架构
c++·人工智能·python·qt·机器学习·ocr
测试员周周9 小时前
【skills5】一份 spec 生成 k6/JMeter/Locust:性能压测 + 全站截图,上线前的双保险
功能测试·网络协议·测试工具·jmeter·http·自动化·集成测试
许彰午10 小时前
95_Python内存管理与垃圾回收
开发语言·python
骄阳如火10 小时前
Python 性能深度剖析:从“被诟病的慢”到“Rust 重塑”的拐点
python
满怀冰雪11 小时前
03-第一个 Paddle 程序:Tensor 创建、计算与设备管理
人工智能·python·paddle
CClaris11 小时前
大模型量化从0到1(九):用 llama.cpp 把模型转成 GGUF 并跑本地推理
人工智能·pytorch·python·深度学习·llama
学编程的小虎11 小时前
SenseVoice微调
人工智能·python·自然语言处理
诸葛说抛光12 小时前
国内大型汽车改装展览会定展 佛山改装 佛山汽车赛事
python·汽车
chouchuang12 小时前
day-030-综合练习-笔记管理器
开发语言·笔记·python
乖巧的妹子12 小时前
Python基础核心知识点详解:内置函数、运算符、字符串方法、数据结构与类型转换
python