簡體   English   中英

如何在'('和下一個空白之間的語句中獲取特定單詞

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM