有没有一种方法可以使用正则表达式在关键字之后但到达“|”之前搜索 x 个字符?
Is there a way to use regex to search for x amount of characters after a keyword but before it reaches '|'?
遍历列表时,将返回以下字符串的示例。我正在尝试将团队名称保存为变量。但是,对于列表中要检查的每个字符串,名称可以是任意数量的字符。
顺便说一句,在将总分保存为变量时,我通过
实现了这一点
pointTotal = re.search("Total:" + '.\w+', eachEntry)
虽然这显然不适用于跨越多个单词的团队名称。
我的目标是对 'Name:' 之后的所有字符(也可以是数字)执行正则表达式搜索,直到到达竖线符号 (|)。最终我会得到 teamName = "Avacado Helmets"
..."|Keypad:6 |Name:Avacado Helmets |Pressed:E |Seconds:15.73 |Question Points:0 |Total:5802"
我希望这个问题不是太复杂,我一直在通过正则表达式测试器进行搜索以尝试找出答案,但我只是觉得我需要一些指导。我刚刚开始使用正则表达式,并为此进行编程,我将不胜感激任何帮助。谢谢。
您可以在此处使用 re.findall
和捕获组:
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
作为@Cary Swoveland said in his comment, you can use positive lookbehind and lookahead to get only the Name value using the Regex (?<=Name:).+?(?= *\|)
,喜欢
import re
string = '|Keypad:6 |Name:Avacado Helmets |Pressed:E |Seconds:15.73 |Question Points:0 |Total:5802'
name = re.search(r'(?<=Name:).+?(?= *\|)', string).group()
print(name) # Avacado Helmets
此外,据我从问题中了解到,如果您想使用此正则表达式将从字符串中获得的所有值分配给全局变量,则可以使用此代码 ([A-Z][^:]+):([^|]+?)(?= *\||$)
lst = re.findall(r'([A-Z][^:]+):([^|]+?)(?= *\||$)', string)
for name, value in lst:
globals()[name] = value
如果它不起作用请告诉我...
遍历列表时,将返回以下字符串的示例。我正在尝试将团队名称保存为变量。但是,对于列表中要检查的每个字符串,名称可以是任意数量的字符。
顺便说一句,在将总分保存为变量时,我通过
实现了这一点pointTotal = re.search("Total:" + '.\w+', eachEntry)
虽然这显然不适用于跨越多个单词的团队名称。
我的目标是对 'Name:' 之后的所有字符(也可以是数字)执行正则表达式搜索,直到到达竖线符号 (|)。最终我会得到 teamName = "Avacado Helmets"
..."|Keypad:6 |Name:Avacado Helmets |Pressed:E |Seconds:15.73 |Question Points:0 |Total:5802"
我希望这个问题不是太复杂,我一直在通过正则表达式测试器进行搜索以尝试找出答案,但我只是觉得我需要一些指导。我刚刚开始使用正则表达式,并为此进行编程,我将不胜感激任何帮助。谢谢。
您可以在此处使用 re.findall
和捕获组:
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
作为@Cary Swoveland said in his comment, you can use positive lookbehind and lookahead to get only the Name value using the Regex (?<=Name:).+?(?= *\|)
,喜欢
import re
string = '|Keypad:6 |Name:Avacado Helmets |Pressed:E |Seconds:15.73 |Question Points:0 |Total:5802'
name = re.search(r'(?<=Name:).+?(?= *\|)', string).group()
print(name) # Avacado Helmets
此外,据我从问题中了解到,如果您想使用此正则表达式将从字符串中获得的所有值分配给全局变量,则可以使用此代码 ([A-Z][^:]+):([^|]+?)(?= *\||$)
lst = re.findall(r'([A-Z][^:]+):([^|]+?)(?= *\||$)', string)
for name, value in lst:
globals()[name] = value
如果它不起作用请告诉我...