简体   繁体   English

如何在'('和下一个空白之间的语句中获取特定单词

[英]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确保它是单词边界。

Demo 演示版

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.

相关问题 编辑边界以消除matplotlib中的绘图中的空白区域 - Editing bounds to get rid of white-space within a plot in matplotlib Python如何使用分割定界符删除CSV上的空白 - Python how to use split delimiter to remove white-space on csv 如何用空白填充信息,而其余部分保持不变? - How to fill the white-space with info while leaving the rest unchanged? 如何使用Selenium和Python在innerText包含前导和尾随空格字符时定位和单击元素 - How to locate and click the element when the innerText contains leading and trailing white-space characters using Selenium and Python 当 textContext 包含前导和尾随空白字符时如何单击按钮? - How to click on the button when the textContext contains leading and trailing white-space characters? 编写空格分隔的文本以使其在Python#2中易于阅读 - Writing white-space delimited text to be human readable in Python #2 将单个用空格分隔的字符串列表转换为整数 - Converting a list of individually white-space separated strings into integers 在Python中编写以空白分隔的文本是人类可读的 - Writing white-space delimited text to be human readable in Python 单独的数据文件负号和空白定界符 - separate datafiles negative sign and white-space delimiter 关于空白填充的成功结果的第2部分 - Part 2 of a successful outcome regarding white-space filling
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM