python - 使用 python 正则表达式删除括号之间的内容

标签 python regex

我有一个像这样的文本文件-

{[a] abc (b(c)d)}

我想删除括号 [] 和 (()) 之间的内容。所以输出应该是 -

 abc

我删除了括号之间的内容但是无法删除此[]之间的内容 我试过下面的代码 -

import re

with open('data.txt') as f:
    input = f.read()
    line = input.replace("{","")
    line = line.replace("}","")
    output = re.sub(r'\(.*\)', "", line)
    print output

输出是-

[a] abc

在我的代码中,我首先替换了 {},然后从 () 中删除了内容。我想在 output = re.sub(r'\(.*\)', "", line) 这一行添加 \[.*\] 。但找不到办法做到这一点。我还在学习python。所以我面临这个问题。请帮忙。

最佳答案

Imo 并不像乍看起来那么容易,您很可能需要一些平衡(递归)方法,这可以通过 newer regex module 实现:

import regex as re

string = "some lorem ipsum {[a] abc (b(c)d)} some other lorem ipsum {defg}"

rx_part = re.compile(r'{(.*?)}')
rx_nested_parentheses = re.compile(r'\((?:[^()]*|(?R))*\)')
rx_nested_brackets = re.compile(r'\[(?:[^\[\]]*|(?R))*\]')

for match in rx_part.finditer(string):
    part = rx_nested_brackets.sub('', 
        rx_nested_parentheses.sub('', 
            match.group(1))).strip()
    print(part)

哪个会产生

abc
defg


模式是

\(         # opening parenthesis
(?:        # non.capturing group
    [^()]* # not ( nor )
    |      # or
    (?R)   # repeat the pattern
)*
\)

关于python - 使用 python 正则表达式删除括号之间的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49915974/

相关文章:

regex - Perl 将正则表达式匹配分配给具有默认值的变量

python - 如何使用python控制Wireshark?如何使用 python 单击/按下 Wireshark 中的按钮

正则表达式 - 查找 2000 到 3000 之间的数字

javascript - 与 .innerHTML 一起传递值

python - 如何进入 Python 虚拟环境并从 shell 脚本在其中运行 shell 命令?

php - 从邮箱字符串中获取电子邮件地址

java - 为什么此标记生成器返回不正确的值?

java - 如何验证 "Hangul-Korean"文本?

python - 属性名称是否在 python 中基于实例消耗内存

python - 如何使用许多小文件加速 Spark Parquet Reader