regex保留一些内容并删除方括号中的所有内容

时间:2018-07-05 13:51:00

标签: python regex

如何删除方括号以及其中的字符串/数字,但仅删除曲线括号并保留其内容。

例如,

This is a (text).[s]This is a sample[22].

应显示为: This is a text. This is a sample.

到目前为止我的尝试:

def _remove_regex(input_text, regex_pattern):
    pattern_lines = re.finditer(regex_pattern, input_text)
    for pattern in pattern_lines:
        input_text = re.sub(pattern.group().strip(), '', input_text)
    return input_text

regex_pattern = '\[\[(?:[^\]|]*\|)?([^\]|]*)\]\]'
_remove_regex(text, regex_pattern)

3 个答案:

答案 0 :(得分:2)

使用正则表达式和str.replace

例如:

import re
s = "This is a (text).[s]This is a sample[22]"
text = re.sub("\[.*?\]", "", s)
text = text.replace("(", "").replace(")", "")
print(text)

输出:

This is a text.This is a sample

答案 1 :(得分:1)

import re
s = 'This is a (text).[s]This is a sample[22].'
re.sub(r'\[[^\]]*\]|[\(\)]', '', s)
# 'This is a text.This is a sample.'

答案 2 :(得分:-3)

您可以尝试此功能: yourSentence = This is a (text).[s]This is a sample[22].

def deleteBracketAndParenthesis (sentence):
     l = []
     for word in list(sentence):
         if ((word.split("(") is None) or (word.split("[") is None):
                l.append(word)
         elif (word.split("(") == null):
                l.append(word.split("(")[1])
     return( "".join(l) )