【问题标题】:how to remove content inside bracket without removing brackets如何在不删除括号的情况下删除括号内的内容
【发布时间】:2021-02-26 06:15:00
【问题描述】:
string="file()(function)(hii)out(return)(byee)"

对于这个字符串,我需要像这样的输出

file()()()out()()

我试过了

string="file()(function)(hii)out(return)(byee)"
string1=re.sub("[\(\[].*?[\)\]]", "", string)
string2=re.sub(r" ?\([^)]+\)", "", string)

print(string1)
print(string2)

得到类似的输出

fileout

file()out

我想要的输出应该是这样的:

file()()()out()()

【问题讨论】:

    标签: python regex string


    【解决方案1】:

    使用正则表达式:捕获括号之间的所有内容,即 (.*?) 并将其替换为空字符串,即 ( )

    import re
    
    x = "file()(function)(hii)out(return)(byee)"
    x = re.sub("\(.*?\)", "()", x)
    print(x)
    

    这将打印出来

    文件()()()输出()()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-11-03
      • 2013-11-17
      • 2017-07-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-07
      相关资源
      最近更新 更多