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

2024-04-25 00:36:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个文本文件像-

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

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

 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。所以我面临这个问题。请帮忙。你知道吗


Tags: and代码importre内容inputoutputdata
3条回答

我试过了,我得到了你想要的结果…我希望我做对了

import re

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

您可以检查字符串是否包含[](<no_parentheses_here>)[no_brackets_here]子字符串,并在存在匹配项时将其删除。你知道吗

import re                                    # Use standard re
s='{[a] abc (b(c)d)}'
rx = re.compile(r'\([^()]*\)|\[[^][]*]|[{}]')
while rx.search(s):                          # While regex matches the string
    s = rx.sub('', s)                        # Remove the matches
print(s.strip())                             # Strip whitespace and show the result
# => abc

参见Python demo

它还将与成对嵌套的(...)[...]一起工作。你知道吗

图案细节

  • \([^()]*\)-(,然后是除()之外的任何0+字符,然后是)
  • |-或
  • \[[^][]*]-[,然后是除[]之外的任何0+字符,然后是]
  • |-或
  • [{}]-匹配{}的字符类。你知道吗

Imo并不像最初看起来那么简单,您很可能需要一些平衡(递归)的方法,这可以通过newer ^{} 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
)*
\)

相关问题 更多 >