1

I have a string like this:

field1:value1 field2:value2

field can have spaces ie. "field name:" but the value field will never have any.

Using a regex what is an easy way extract the field value pairs into numerical groups without knowing the field name beforehand?

I'm using python b

Thanks

3 Answers 3

7
>>> subject = "field name 1:value1 field2:value2  field name3:value3"
>>> d = { match.group(1): match.group(2)
...       for match in re.finditer(r"([^:]+):(\S+)\s*", subject)
...     }
>>> d
{'field name 1': 'value1', 'field2': 'value2', 'field name3': 'value3'}

This is using a dictionary comprehension that's populated using this regex:

([^:]+) # one or more characters except :  (--> group(1))
:       # a literal :
(\S+)   # one or more non-whitespace characters (--> group(2))
\s*     # optional trailing whitespace (before the next match)
Sign up to request clarification or add additional context in comments.

Comments

2

You can use re.findall() to do what you want:

>>> data = "field1:value1 field2:value2 field with space:something"
>>> re.findall(r'\s*([^:]+):(\S+)', data)
[('field1', 'value1'), ('field2', 'value2'), ('field with space', 'something')]

Comments

0

Something like this, perhaps?

([^:]+:[^ ]*)*

Comments

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.