【问题标题】:Remove text between () and []删除 () 和 [] 之间的文本
【发布时间】:2013-01-13 20:21:56
【问题描述】:

我有一个很长的文本字符串,其中包含()[]。我正在尝试删除括号和方括号之间的字符,但我不知道如何。

列表与此类似:

x = "This is a sentence. (once a day) [twice a day]"

这个列表不是我正在使用的,但非常相似,而且要短得多。

【问题讨论】:

  • 请展示您的尝试(通过编辑您的问题而不是添加评论),人们会为您指明正确的方向。
  • 可以嵌套()[],例如"[a [(b] ([c))]]"?

标签: python python-2.7


【解决方案1】:

这应该适用于括号。正则表达式将“消耗”它匹配的文本,因此它不适用于嵌套括号。

import re
regex = re.compile(".*?\((.*?)\)")
result = re.findall(regex, mystring)

或者这会找到一组括号,只需循环查找更多:

start = mystring.find("(")
end = mystring.find(")")
if start != -1 and end != -1:
  result = mystring[start+1:end]

【讨论】:

  • 我不知道为什么这个答案被标记为正确。要求 remove 文本的问题,而不是返回它。我有同样的需求(删除某些字符之间的文本),@jvallver 的回答帮助了我。
  • 这与 OP 要求的相反
【解决方案2】:

运行此脚本,它甚至可以使用嵌套括号。
使用基本的逻辑测试。

def a(test_str):
    ret = ''
    skip1c = 0
    skip2c = 0
    for i in test_str:
        if i == '[':
            skip1c += 1
        elif i == '(':
            skip2c += 1
        elif i == ']' and skip1c > 0:
            skip1c -= 1
        elif i == ')'and skip2c > 0:
            skip2c -= 1
        elif skip1c == 0 and skip2c == 0:
            ret += i
    return ret

x = "ewq[a [(b] ([c))]] This is a sentence. (once a day) [twice a day]"
x = a(x)
print x
print repr(x)

以防万一你不运行它,
这是输出:

>>> 
ewq This is a sentence.  
'ewq This is a sentence.  ' 

【讨论】:

    【解决方案3】:

    你可以使用 re.sub 函数。

    >>> import re 
    >>> x = "This is a sentence. (once a day) [twice a day]"
    >>> re.sub("([\(\[]).*?([\)\]])", "\g<1>\g<2>", x)
    'This is a sentence. () []'
    

    如果要删除 [] 和 (),可以使用以下代码:

    >>> import re 
    >>> x = "This is a sentence. (once a day) [twice a day]"
    >>> re.sub("[\(\[].*?[\)\]]", "", x)
    'This is a sentence.  '
    

    重要提示:此代码不适用于嵌套符号

    说明

    第一个正则表达式将 ([ 分组到第 1 组(用括号括起来),将 )] 分组到第 2 组,匹配这些组和它们之间的所有字符。匹配后,匹配的部分被第 1 组和第 2 组替换,最后的字符串在括号内没有任何内容。第二个正则表达式是自解释的 -> 匹配所有内容并替换为空字符串。

    -- 由 comment 修改为 Ajay Thomas

    【讨论】:

    • 如果x = "ewq[a [(b] ([c))]]" 不起作用,它会给出'ewq )]]' 而不是'eqw'...
    • @paddila 我知道,但 Tic 没有提及嵌套符号。
    • 我评论过问他这件事..他还没有回复
    • 有人能解释一下这里使用的正则表达式吗?
    • @markroxor 第一个正则表达式将 '(' 和 ']' 分组到第 1 组(用括号括起来)和 ')' 和 ']' 到第 2 组,匹配这些组和所有字符介于两组之间。匹配后,匹配的部分被第 1 组和第 2 组替换,最后的字符串在括号内没有任何内容。第二个正则表达式是自解释的 -> 匹配所有内容并用空字符串替换。希望对你有帮助
    【解决方案4】:

    这是一个类似于@pradyunsg's answer 的解决方案(它适用于任意嵌套括号):

    def remove_text_inside_brackets(text, brackets="()[]"):
        count = [0] * (len(brackets) // 2) # count open/close brackets
        saved_chars = []
        for character in text:
            for i, b in enumerate(brackets):
                if character == b: # found bracket
                    kind, is_close = divmod(i, 2)
                    count[kind] += (-1)**is_close # `+1`: open, `-1`: close
                    if count[kind] < 0: # unbalanced bracket
                        count[kind] = 0  # keep it
                    else:  # found bracket to remove
                        break
            else: # character is not a [balanced] bracket
                if not any(count): # outside brackets
                    saved_chars.append(character)
        return ''.join(saved_chars)
    
    print(repr(remove_text_inside_brackets(
        "This is a sentence. (once a day) [twice a day]")))
    # -> 'This is a sentence.  '
    

    【讨论】:

    • 乍一看很复杂,但比我的要好(而且绝对是公认的(我的观点))
    • 优秀的答案。
    【解决方案5】:

    您可以再次拆分、过滤和连接字符串。如果您的括号定义明确,则应该执行以下代码。

    import re
    x = "".join(re.split("\(|\)|\[|\]", x)[::2])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-03
      • 1970-01-01
      相关资源
      最近更新 更多