[英]How to get specific word in a statement between '(' and the next white-space
因此,我有一堆具有基本设置TeamName (GMName - Tier)
的字符串,我试图找到一种从该字符串获取GMName的好方法。
我尝试使用此正则表达式: \\(\\w*\\s
但这给了我(GMName
然后我必须以某种方式解析GMName才能获得GMName。我是否可以在单个脚本中使用正则表达式或某些Python函数行得到我想要的?
如果只希望它检查周围的字符串而不会被捕获到匹配文本中,则需要使用环顾四周。 您这个正则表达式,
(?<=\()\w*\b
在这里, (?<=\\()
确保单词前面有文字(
而\\b
确保它是单词边界。
示例python代码,
import re
s = 'TeamName (GMName - Tier)'
arr = re.findall(r'(?<=\()\w*\b', s)
print(arr)
印刷品
['GMName']
您可以在后括号中使用后向标记,也可以使用捕获组。
向后看
>>> 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"
捕获组
>>> 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.