0

As an example of the type of content I have to parse off of a ticket:

Name:
snakeoil
Host:
foobar

{block}
  email: some data here
  url: http://foo
  date: 01/02/16
{block}

I can identify the 'key', which is any word typically ending in a colon

I could use the regex module to do a match like ^\w$ to extract the key, but I must handle both the case where the value is in the same line vs in the subsequent line.

Having to fetch the word in the next line is what I can't think of how to address cleanly and/or effectively.

2 Answers 2

2

You can still use regex if it's well formed,

>>> re.findall('(.*?):\n(.*)$', content, re.MULTILINE)
[('Name', 'snakeoil'), ('Host', 'foobar')]
Sign up to request clarification or add additional context in comments.

2 Comments

To get both the multilines and on-same-line, I guess the regexp should be more like r'(\w*?):\n?(.*)$' ?
The regex from @DainDwarf does it. Thanks!
1

If You need email, url and date too:

>>> re.findall('\s*(.*?):[\n\s]?(.*)$', s, re.MULTILINE)
[('Name', 'snakeoil'), ('Host', 'foobar'), ('email', 'some data here'), ('url', 'http://foo'), ('date', '01/02/16')]

if not, @QiangJin solution is good

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.