s = "[Guide] Strength (STR are long) is recommended on Warriors (Warriors -> Berserker)"
re.findall('\(([^\)]+)\)', s) # returns all matches
>>> ['STR are long', 'Warriors -> Berserker']
re.findall('\(([^\)]+)\)', s)[0] # returns the first match which is what you want.
>>> 'STR are long'
>>> import re
>>> s="[Guide] Strength (STR) is recommended on Warriors (Warriors -> Berserker)"
>>> result = re.split(r"\s+(?=[^()]*(?:\(|$))", s)
>>> next((i[1:-1] for i in result if i[0]=='(' and i[-1]==')'),'No sub-strings that are surrounded by parenthesis')
'STR'
>>>
注意:在这里,如果字符串不包含任何用括号括起来的子字符串,它将输出'No sub-strings that are surrounded by parenthesis',如果不需要,您可以这样做:
^{pr2}$
或者:
>>> [i[1:-1] for i in result if i[0]=='(' and i[-1]==')'][0]
使用
re.search
和@kingram解释的group,或者使用re.findall
,然后选择第一个元素。在注意:
如果字符串s中没有匹配项,
re.findall
将返回一个空的列表,而re.search
将返回一个None
对象。在re.search
返回第一个匹配项.group(1)
返回第一个捕获组的内容,即([^)]+)
或
re.split
:注意:在这里,如果字符串不包含任何用括号括起来的子字符串,它将输出
^{pr2}$'No sub-strings that are surrounded by parenthesis'
,如果不需要,您可以这样做:或者:
相关问题 更多 >
编程相关推荐