简体   繁体   中英

How can I use regex in Python to extract the string?

I have to extract a string from a network response which looks like shown below:

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

Here is your encrypted text:
96a1e3424f4cfa23db131173d7f8c93396a1e3424f4cfa23db131173d7f8c933182bc4e99a47abb5deaa51741527dd2b478746563aecc40d5d6f6597370338a7

Some more text:

The response contains "\\r\\n" or if checked on Linux, then "\\n"

How can I extract the hash from above message?

I wrote something like below but it did not extract the hash:

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)

Thanks.

Read the input one line at a time (using readlines() or split('\\n') ) and do this:

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

If it's okay that you don't use regex, try it:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM