如何在Python中使用正则表达式来提取字符串?

问题描述 投票:0回答:2

我必须从网络响应中提取一个字符串,如下所示:

Hello, did you get this message?
I want to check it,
let me know!

Here is your encrypted text:
96a1e3424f4cfa23db131173d7f8c93396a1e3424f4cfa23db131173d7f8c933182bc4e99a47abb5deaa51741527dd2b478746563aecc40d5d6f6597370338a7

Some more text:

响应包含“\ r \ n”或如果在Linux上选中,则“\ n”

如何从上面的消息中提取哈希?

我写了类似下面的东西,但它没有提取哈希:

import re

# data corresponds to network response which contains the \r\n characters

matchObj = re.match( r'(.*?)your encrypted text:\r\n(.*)\r\n.*', data)

if matchObj:
    print matchObj.group(2)

谢谢。

python regex
2个回答
1
投票

一次读取一行输入(使用readlines()split('\n'))并执行以下操作:

for line in lines:
    match = re.match('^([0-9a-f]+)$', line)
    if match:
        print(match.groups(1)[0])

1
投票

如果您没有使用正则表达式,请尝试:

lines = open(file_name, 'r').read().splitlines()

for i, line in enumerate(lines):
    if line.strip() == "your encrypted text:":
        my_text = lines[i + 1]
        break
© www.soinside.com 2019 - 2024. All rights reserved.