UT-
UT-

Reputation: 83

Regex to remove parentheses

I have a TreeMap in Java where some of the keys are of the type ABC (1), ABC (2) with only numbers inside the parentheses.

I would like to remove the (1) and (2) along with the preceding blank space and end up with only ABC.

I am really bad at regex, I know it must be a very simple regex for some of the members here, but I would like to find the regex to replace the " (1)" and " (2)" with "".

Thanks a lot for any help in advance.

Upvotes: 1

Views: 1418

Answers (1)

Mark A. Fitzgerald
Mark A. Fitzgerald

Reputation: 1249

key.replaceAll(" \\([\\d]+\\)", "")

The line above should return the key with such space-prefixed parenthesized numbers removed. Escaping of the parentheses makes them a literal match, rather than a submatch grouping/capture operator.

I used RegexPlanet's regex tester for java to test the regex, and the String#ReplaceAll documentation to verify Java replacement of a regex match usage.

Upvotes: 3

Related Questions