Python中的Regex搜索:排除带有'line 22'的端口22行

2024-09-27 00:23:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我当前在python中的regex搜索查找带有' 22 '的行,但是我想排除带有' line 22 '的行。我如何用Regex来表达这个?我会'.*(^line) 22 .*$'

import re

sshRegexString='.* 22 .*$'
sshRegexExpression=re.compile(sshRegexString)

Tags: importrelineregexcompile我会sshregexstringsshregexexpression
1条回答
网友
1楼 · 发布于 2024-09-27 00:23:03

您可以在没有regex帮助的情况下实现查找包含 22 但不包含line 22 的行的当前需求

只需检查这些文本是in还是not in列表中的字符串。下面是一个Python demo(我假设列表中有行,但可以调整为逐个处理从文件中读取的行):

lines = ['Some text 1 line 22 here', 'Some text 2 Text2 22 here', 'Some text 3 Text3 22 here']
good = [s for s in lines if ' 22 ' in s and 'line 22 ' not in s]
print(good) # the first lines[0] is not printed!

相关问题 更多 >

    热门问题