python - 确定一个字符是否不在索引处的一组括号中?

标签 python

我正在尝试确定字符是否未包含在字符串 s 中特定索引处的一组括号中。假设:

s = '(A.(B|A)).A'

然后是字符 '.' 的索引是 2 和 9。但是,只有 '.'索引 9(即 s[9])未包含在括号中。我怎样才能做到这一点?

编辑:我也想知道字符未包含在括号中的索引。

最佳答案

注意:这仅在括号平衡时有效。

如果你正在寻找特定字符的索引,它没有被括号括起来,那么你可以这样做

def checker(data, char_checked):
    opened, result = 0, []
    for idx, char in enumerate(data):
        if char == char_checked and opened == 0 and char != "(":
            result.append(idx)
        if char == "(":
            opened += 1
        elif char == ")":
            opened -= 1
    return result

assert checker('(A.(B|A)).A', '.')  == [9]
assert checker('(A.(B|A)).A', 'A')  == [10]
assert checker('(A.(B|A)).A', 'C')  == []

如果你要查找所有没有括在括号中的字符,那么你可以像这样稍微改变一下

def checker(data):
    opened, result = 0, []
    for idx, char in enumerate(data):
        if opened == 0 and char != "(":
            result.append([idx, char])
        if char == "(":
            opened += 1
        elif char == ")":
            opened -= 1
    return result

assert checker('(A.(B|A)).A') == [[9, '.'], [10, 'A']]
assert checker('(A.(B|A))')   == []

关于python - 确定一个字符是否不在索引处的一组括号中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22508932/

相关文章:

python - 如何使用工作或学校帐户将 SharePoint Online (Office365) Excel 文件读入 Python,特别是 pandas?

python - 如何使用 seaborn 为我的 DataFrame 创建堆叠条形图

python - Django 中的 "app"是什么?

python - Gurobi 线性约束

python - mongodb:查询列表中的值(而不是对象)

python - 试图操纵数据,将列表分配给更高列表中的第一项,第二项将是有关该列表的信息

python - 在 Python 中转换时间

python - 如何在 Windows 上安装 gevent?

基于 Python 的作业调度程序,具有依赖性解析

python TCPServer 地址已在使用中,但我关闭服务器并使用 `allow_reuse_address`