正则表达式查找关键字并打印匹配的整行

2024-09-27 07:26:20 发布

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

我需要创建一个在python中使用的regexp,其中一个关键字将在输出中匹配&;应显示完全匹配的整条线路,请协助

Some_output = "hello how are you something. \nhello how are you2 something.\nhello how are you3 
something."
Search_String ="you2"
Expected Output - how are you2 something.
vv = re.findall(r'.*you2.*',Some_output)
print(vv)  - returns nothing 

Tags: youhellooutputsome关键字aresomething线路
2条回答

我会将您的输入标记化/拆分为一系列句子,然后使用列表理解来查找匹配的句子:

inp = "hello how are you something. \nhello how are you2 something.\nhello how are you3 something."
sentences = inp.split('\n')
search = 'you2'
matches = [s for s in sentences if re.search(r'\b' + search + r'\b', s)]
print(matches)  # ['hello how are you2 something.']

首先,将字符串转换为一个列表,然后查找与Search_String标记匹配的任何行

Some_output = "hello how are you something. \nhello how are you2 something.\nhello how are you3 something."
LINES = Some_output.split('\n')
Search_String = "you2"
for LINE in LINES:
    if re.search(r'\b{}\b'.format(Search_String), LINE):
        print(LINE)

相关问题 更多 >

    热门问题