首页 > 解决方案 > 在Python中检索括号中的第一个单词

问题描述

我在此处搜索并阅读了一些代码正则表达式以返回括号之间的文本

但是例如说我有以下字符串

“[指南] 力量(STR)推荐给勇士(勇士 -> 狂战士)”

我将如何仅输出“STR”而不输出 (Warriors -> Berserker) ?

谢谢!

标签: pythonparentheses

解决方案


考虑以下字符串,

s = 'I am John (John (M) Doe)'

有效括号中的第一个单词应该是“John (M) Doe”而不是“John (M”。以下代码将计算开括号和闭括号:

opn = 0
close = 0
new_str = ''
add = False
for i in s:
    if not add:
        if i == '(':
            opn += 1
            add = True
    else:
        if i == '(':
            new_str += i
            opn += 1
        elif i == ')':
            close += 1
            if opn == close:
                break
            else:
                new_str += i
        else:
            new_str += I

print(new_str)

这产生:

John (M) Doe

希望这可以帮助!


推荐阅读