Search code examples
pythonregexpython-re

Is there a way to use regex to search for x amount of characters after a keyword but before it reaches '|'?


When iterating through a list, an example of a string below would be returned. I'm trying to save the team name as a variable. However, for each string to be examined within the list, the name can be any quantity of characters.

As an aside, when saving the total score as a variable, I achieved this through

pointTotal = re.search("Total:" + '.\w+', eachEntry) 

though this will obviously not work for team names that span over multiple words.

My goal is to perform a regex search on all the characters (could also be numbers) that follow 'Name:' till it reaches the pipe symbol (|). Ultimately I would be able to end up with teamName = "Avacado Helmets"

..."|Keypad:6 |Name:Avacado Helmets  |Pressed:E  |Seconds:15.73  |Question Points:0  |Total:5802"

I hope that this question was not too convoluted, I've been searching through the regex testers to try and figure it out, but I just think I need a bit of guidance. I'm just finding my feet with regex, and programming for that matter, and I would appreciate any help. Thank you.


Solution

  • You may use re.findall here with a capture group:

    inp = "|Keypad:6 |Name:Avacado Helmets |Pressed:E |Seconds:15.73 |Question Points:0 |Total:5802"
    name = re.findall(r'\|Name:(.*?)\s*(?:\||$)', inp)[0]
    print(name)  # Avocado Helmets