0

Here is my string:

string ='First: Michael, Second: Dennis, Third: Michael, \nAssists: Michael, Scoring: Michael, Rebounds: Peter, Steals: Dennis'

This strings holds many items which represent an accolade and their recipient. I'm attempting to first determine who was the winner of the 'first' accolade, and then pull out all other items involving that recipient.

So in this case, we check who the winner of the first recipient is (Michael), and then we pull out all of the accolades (along with the name Michael) involving Michael.

So the result should be something like:

'First: Michael, Third: Michael, Assists: Michael, Scoring: Michael'

I was trying to utilize back refrencing along with look-arounds, but it got a little messy

import re
string ='First: Michael, Second: Dennis, Third: Michael, \nAssists: Michael, Scoring: Michael, Rebounds: Peter, Steals: Dennis'
re.findall('(?=First: (\w+)), (?=\w+: \w+, )|(\w+: \1,)+', string)
1
  • 1
    I really think you should split it up into different lines and get the matches that way. Commented Aug 2, 2017 at 21:19

1 Answer 1

1

So - this is a nice "puzzle trivia" to do if you want to do it with regexps (and I might even give it a try later) - but all in allyou will have fragile code - it won't work if your input data format change a bit, and it will be a maintenance nightmare.

Now, the "steady" way: pick that string - split it at "," - then split each segment at the ":", strip each component, and create a Python dictionary out of that. Then it is trivial to use a dictionary comprehension expression to extract your desired data:

def get_first_accolade(text):
    parts = text.split(",")
    data = {}
    for item in parts:
         key, value = item.split(",")
         data[key.strip()] = value.strip()
    result = {key: value for key, value in data.items() if value == data["first"]}
    return result
Sign up to request clarification or add additional context in comments.

3 Comments

This didn't work for me. ValueError: need more than 1 value to unpack
I see. I was hoping there was an elegant way to do it with one of RE's group methods.
It probably is possible. It will feel chalenging to get to it, and fun, but I doubt it could be called "elegant" :-)

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.