[英]How to get specific word in a statement between '(' and the next white-space
So I have a bunch of strings that have this basic setup TeamName (GMName - Tier)
I'm trying to find a good way to get the GMName from that string. 因此,我有一堆具有基本设置
TeamName (GMName - Tier)
的字符串,我试图找到一种从该字符串获取GMName的好方法。
I tried using this regex: \\(\\w*\\s
but that gives me (GMName
which I would then have to parse in some way to get the GMName only. Is there a regex or some Python function that I can use in a single line to get what I want? 我尝试使用此正则表达式:
\\(\\w*\\s
但这给了我(GMName
然后我必须以某种方式解析GMName才能获得GMName。我是否可以在单个脚本中使用正则表达式或某些Python函数行得到我想要的?
You need to use look arounds if you just want it to check for surrounding strings without them getting captured into the match text. 如果只希望它检查周围的字符串而不会被捕获到匹配文本中,则需要使用环顾四周。 You this regex,
您这个正则表达式,
(?<=\()\w*\b
Here, (?<=\\()
ensures, the word is preceded by literal (
and \\b
ensures it is a word boundary. 在这里,
(?<=\\()
确保单词前面有文字(
而\\b
确保它是单词边界。
Sample python code, 示例python代码,
import re
s = 'TeamName (GMName - Tier)'
arr = re.findall(r'(?<=\()\w*\b', s)
print(arr)
Prints, 印刷品
['GMName']
You can either use a lookbehind for the open paren, or use a capture group. 您可以在后括号中使用后向标记,也可以使用捕获组。
Lookbehind 向后看
>>> pat = re.compile(r"""
... (?<=\() # asserts that a literal ( precedes the following:
... \S+ # one or more non-spaces
... """, re.X)
>>> pat.search("TeamName (GMName - Tier)").group()
"GMName"
Capture groups 捕获组
>>> pat = re.compile(r"""
... \( # a literal (
... (\S+) # capture one or more non-space characters
... """, re.X)
>>> pat.search("TeamName (GMName - Tier)").group(1)
"GMName"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.