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

时间:2018-11-25 04:44:52

标签: python regex

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

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)

谢谢。

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分: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