Reputation: 13
I kind of wish select the domain name from string and put it into a dictionary. So i use re.match()
and re.groupdict()
on this string:
Location: hk USER: Will Lee PASS: 1234 INFO: www.hotmail.com
The code is
re.match(r"(?P<Domain>\.([a-zA-Z0-9]+?)\.(?=com))",str).groupdict()
This should make a dictionary which key is "Domain" and value is "hotmail", but somehow it returned:
AttributeError: 'NoneType' object has no attribute 'groupdict'
How can i fix this?
Upvotes: 1
Views: 4388
Reputation: 58
you should use re.match with (?P<..dict key...>) and groupdict(). code:
import re
s="Location: hk USER: Will Lee PASS: 1234 INFO: www.hotmail.com"
yourDict = re.match(r"^Location: (?P<Location>\w+?) USER: (?P<User>.+?(?= PASS: .+? INFO: .+$)) PASS: (?P<Pass>.+?(?= INFO: .+$)) INFO: (?P<Doman>.+$)",s).groupdict()
=> {'User': 'Will Lee', 'Doman': 'www.hotmail.com', 'Location': 'hk', 'Pass': '1234'}
Upvotes: 1
Reputation: 174816
Use re.search
instead of re.match
because match tries to find the text from the start. And also you need to give the dot inside the lookahead which asserts capture one or more alphanumeric characters followed by the string .com
>>> re.search(r'(?P<Domain>[a-zA-Z0-9]+)(?=\.com)', s).groupdict()
{'Domain': 'hotmail'}
Upvotes: 3