Reputation: 1275
I am using the following regex to remove items in a sentence that falls within brackets
\(.*?\)
So in this sentence anything between (DFKJERLjDLJLF) gets removed.
But if there are more than one brackets in a sentence, I want to target only the last bracket. How do I change my regex?
So in this sentence (only) the last bracket and its contents (DFKJERLjDLJLF) gets removed.
Update: I tried using \s\([^)]+\)$
in my regex tool but it is not matching
Upvotes: 2
Views: 903
Reputation: 667
.*(\(.*?\))
.* matches every character and moves the position to the end, when it bounce back
and then (\(.*?\))
find the first match in (), i.e. the last match from the start.
Upvotes: 4
Reputation: 1227
A python solution to this is:
def remove_last_brackets(string):
return re.sub(r'^(.*)\(.*?\)?([^()]*)$', lambda x: x.group(1) + x.group(2), string)
Upvotes: 1
Reputation: 737
This is hard to answer without language context.
The global flag, supported on most regex systems, allows you to match all occurrences of a string directly.
Alternatively, you could store the first location of a match and then start future searches at that location, and repeat until there are no matches.
Upvotes: 0