0

I have a question regarding regex in Python.

I have key-value pairs separated by | such as this:

"key1: value | key2: value"

I need help to retrieve the keys and the values for each pairs using regex patterns:

>>> import re
>>> value_pairs = "key1: value | key2: value"
>>> pairs = re.match('regex-pattern', value_pairs)
>>> print pairs
(key1, value)
(key2, value)

2 Answers 2

1

You can also do this without a regex:

>>> value_pairs = "key1: value | key2: value"
>>> dict([ex.strip() for ex in e.split(':')] for e in value_pairs.split('|'))
{'key2': 'value', 'key1': 'value'}

Which works for a longer groups of pairs as well:

>>> value_pairs = "key1: value1 | key2: value 2 | key3: value3"
>>> dict([ex.strip() for ex in e.split(':')] for e in value_pairs.split('|'))
{'key3': 'value3', 'key2': 'value 2', 'key1': 'value1'}
Sign up to request clarification or add additional context in comments.

1 Comment

+1 You don't really need the extra outer [] in dict().
0

Use re.findall to get multiple matches:

>>> import re
>>> s = "key1: value | key2: value"
>>> re.findall(r'([^\s|:]+):\s*([^\s|:]+)', s)
[('key1', 'value'), ('key2', 'value')]

As you can see in the above example, re.findall returns a list of tuples if there are multiple groups in the pattern.

2 Comments

thanks for the solution. How can I modify the regex if the value has more than 1 token, for example if I have key1: coca cola this current regex will return [('key', 'coca')] but I wish to return [('key', 'coca cola')]
@Juli, Try [(key, value.strip()) for key, value in re.findall(r'([^\s|:]+):\s*([^|:]+)', s)]

Your Answer

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.