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.
CodePudding user response:
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
CodePudding user response:
As @Gurmanjot Singh said in his comment, you can use positive lookbehind and lookahead to get only the Name value using the Regex (?<=Name:)[^|] ?(?=\s*\|), like
import re
string = '|Keypad:6 |Name:Avacado Helmets |Pressed:E |Seconds:15.73 |Question Points:0 |Total:5802'
name = re.search(r'(?<=Name:)[^|] ?(?=\s*\|)', string).group()
print(name) # Avacado Helmets
And also, as far as I've understood from the question, you can use this code if you wanted to assign all the values you get from the string into a global variables using this Regex ([A-Z][^:] ):([^|] ?)(?=\s*\||$)
lst = re.findall(r'([A-Z][^:] ):([^|] ?)(?=\s*\||$)', string)
for name, value in lst:
globals()[name] = value
Tell me if its not working...
