2

I have a piece of text and I've got to parse usernames and hashes out of it. Right now I'm doing it with two regular expressions. Could I do it with just one multiline regular expression?

#!/usr/bin/env python
import re
test_str = """
Hello, UserName.
Please read this looooooooooooooooong text. hash
Now, write down this hash: fdaf9399jef9qw0j.
Then keep reading this loooooooooong text.
Hello, UserName2.
Please read this looooooooooooooooong text. hash
Now, write down this hash: gtwnhton340gjr2g.
Then keep reading this loooooooooong text.
"""
logins = re.findall('Hello, (?P<login>.+).',test_str)
hashes = re.findall('hash: (?P<hash>.+).',test_str)
asked May 25, 2010 at 9:08

3 Answers 3

5

Try this:

re.findall(r'Hello, (?P<login>[^.]+)\..+?hash: (?P<hash>[^.]+)', test_str, re.S)
answered May 25, 2010 at 9:16
Sign up to request clarification or add additional context in comments.

1 Comment

or even: re.findall(r'(?s)Hello, (?P<login>[^.]+)\..+?hash: (?P<hash>[^.]+)', test_str) (that is, include the flag inside the pattern)
2
name_hash_pair = re.findall('Hello, ([^.]+).*?hash: ([^.]+)', test_str, re.DOTALL)
#gives [('UserName', 'fdaf9399jef9qw0j'), ('UserName2', 'gtwnhton340gjr2g')]
answered May 25, 2010 at 9:17

Comments

2

A simple pyparsing version:

from pyparsing import *
username = Word(alphas,alphanums+"_")
hash = Word(alphanums)
patt = ("Hello," + username("username") + '.' + 
 SkipTo("write down this hash:", include=True) + 
 hash("hash"))
for tokens,start,end in patt.scanString(test_str):
 print tokens.hash, '->', tokens.username
# or to build a dict
hashNameLookup = dict((t.hash, t.username) 
 for t,s,e in patt.scanString(test_str))

Prints:

fdaf9399jef9qw0j -> UserName
gtwnhton340gjr2g -> UserName2
answered May 25, 2010 at 12:35

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.