Regex Python 3.x
Regex Python 3.x
My string is:
s = '"location":"state":"WA","active":true'
I want to get a regex expression so I can capture the following:
group 1: location":
group 2: state":
group 3: active":
Since these 3 words all end with ":
I have tried the following regex, but it is not working:
"[(a-zA-Z)*]+":
I need to capture via 3 groups.
2 Answers
2
This works fine.
>>> re.findall("([a-zA-Z]+)":", s)
['location', 'state', 'active']
Or you can use two steps to complete it.
First, use re.findall
with [a-zA-Z]+":
to find 3 groups.
re.findall
[a-zA-Z]+":
>>> re.findall("[a-zA-Z]+":", s)
['location":', 'state":', 'active":']
Second, replace ":
with empty: r.replace("":", "")
":
r.replace("":", "")
>>> res = re.findall("[a-zA-Z]+":", s)
>>> res
['location":', 'state":', 'active":']
>>> for r in res:
... r.replace("":", "")
...
'location'
'state'
'active'
I was able to capture it with a simple (r'w+":')
(r'w+":')
>>> import re
>>> s = '"location":"state":"WA","active": True'
>>> a = re.compile(r'w+":')
>>> location, state, active = a.findall(s)
>>> location, state, active
('location":', 'state":', 'active":')
Thanks for contributing an answer to Stack Overflow!
But avoid …
To learn more, see our tips on writing great answers.
Required, but never shown
Required, but never shown
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
I don't think you want to capture in three separate groups, but rather match the regex three times. Groups are usually for matching things that you know where they are, to put it simply.
– clabe45
Sep 14 '18 at 0:51