Chris Nielsen
Chris Nielsen

Reputation: 849

Python regular expression to remove all square brackets and their contents

I am trying to use this regular expression to remove all instances of square brackets (and everything in them) from strings. For example, this works when there is only one pair of square brackets in the string:

import re
pattern = r'\[[^()]*\]'
s = """Issachar is a rawboned[a] donkey lying down among the sheep pens."""
t = re.sub(pattern, '', s)
print t

What I get is correct:

>>>Issachar is a rawboned donkey lying down among the sheep pens.

However, if my string contains more than one set of square brackets, it doesn't work. For example:

s = """Issachar is a rawboned[a] donkey lying down among the sheep pens.[b]"""

I get:

>>>Issachar is a rawboned

I need the regular expression to work no matter how many square brackets are in the string. Correct answer should be:

>>>Issachar is a rawboned donkey lying down among the sheep pens.

I have researched and tried many permutations to no avail.

Upvotes: 16

Views: 26057

Answers (3)

Aiden
Aiden

Reputation: 117

For Numbers inside the brackets (No Alphabets), e.g. [89], [23], [11], etc., this is the pattern to use.

import re

text = "The[TEXT] rain in[33] Spain[TEXT] falls[12] mainly in[23] the plain![45]"
pattern = "\[\d*?\]"
numBrackets = re.findall(pattern, text)

print(numBrackets)

Output:

['[33]', '[12]', '[23]', '[45]']

Upvotes: 0

falsetru
falsetru

Reputation: 369444

By default * (or +) matches greedily, so the pattern given in the question will match upto the last ].

>>> re.findall(r'\[[^()]*\]', "Issachar is a rawboned[a] donkey lying down among the sheep pens.[b]")
['[a] donkey lying down among the sheep pens.[b]']

By appending ? after the repetition operator (*), you can make it match non-greedy way.

>>> import re
>>> pattern = r'\[.*?\]'
>>> s = """Issachar is a rawboned[a] donkey lying down among the sheep pens.[b]"""
>>> re.sub(pattern, '', s)
'Issachar is a rawboned donkey lying down among the sheep pens.'

Upvotes: 15

Scovetta
Scovetta

Reputation: 3152

Try:

import re
pattern = r'\[[^\]]*\]'
s = """Issachar is a rawboned[a] donkey lying down among the sheep pens.[b]"""
t = re.sub(pattern, '', s)
print t

Output:

Issachar is a rawboned donkey lying down among the sheep pens.

Upvotes: 6

Related Questions