python 重新正则表达式

标签 python regex

我有一个字符串:

A = '\r\nGigabitEthernet1/0/26  unassigned      YES unset  down                  down    \r\nGigabitEthernet1/0/27  unassigned      YES unset  down                  down    \r\nGigabitEthernet1/0/28  unassigned      YES unset  down                  down    \r\nSW-P-24#                                       '

我的正则表达式是

r'\\r?\\n?.{0,100}\s{0,40}$'

我的目标是用'\\r\\n'替换'\r\nSW-P-24#'

所以我的代码是

re.sub(r'\s*\\r?\\n?.{0,100}\s{0,40}$', '\\r\\n', A)

我的期望返回是

'\r\nGigabitEthernet1/0/26  unassigned      YES unset  down                  down    \r\nGigabitEthernet1/0/27  unassigned      YES unset  down                  down    \r\nGigabitEthernet1/0/28  unassigned      YES unset  down                  down    \r\n'

但是 Python 返回:

'\r\nGigabitEthernet1/0/26  unassigned      YES unset  down                  down    \r\nGigabitEthernet1/0/27  unassigned      YES unset  down                  down    \r\nGigabitEthernet1/0/28  unassigned      YES unset  down                  down    \r\nSW-P-24#                                       '

什么是正确的代码?

最佳答案

问题出在 \\r?\\n?

首先,原始前缀不需要双斜杠,然后“0 或 1”标志会混淆正则表达式引擎。

在 CR+LF 组上使用向后查找似乎可行(并且该技巧允许用空字符串替换而不是重复 CR+LF 字符串):

re.sub(r'(?<=\r\n).{0,100}\s{0,40}$', '', A)

但是,我不确定您是否只想删除最后一行,在这种情况下,不需要正则表达式:

"\r\n".join(A.split("\r\n")[:-1])

关于 python 重新正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41333242/

相关文章:

python - Python 中字符串的基数排序

regex - SED:将现有模式插入同一行的其他几个地方

php - 为什么 PHP preg_* 函数需要正则表达式分隔符?

r - 如何找到只知道 r 中第一个的两个单词模式

python - 如何加载用 tf.keras.models.save_model 保存的训练模型的权重?

python - 如何通过关系模型选择所有对象

python - 如何在 AWS Lambda 中模拟 multiprocessing.Pool.map()?

python - “If”语句和来自命令行的一行 Python 脚本

regex - 从 map 中检索散列键

PHP替换句子中连续出现的字符