I am looking for a regular expression that will replace parentheses and the strings within them if the string anything that is not a digit.
The string can be any combination of characters including numbers, letters, spaces etc.
For example:
(3) will not be replaced
(1234) will not be replaced
(some letters) will be replaced
(some letters, spaces - and numbers 123) will be replaced
So far I have a regex that will replace any parentheses and its content
str = str.replaceAll("\\(.*?\\)","");
I am not good with the syntax of
replaceAll, so I am just going to write the way you have written it. But I think I can help you with the regex.Try this Regex:
Demo
OR an even better one:
Demo
Explanation(for 1st Regex)
\(- matches opening paranthesis(?=[^)]*[a-zA-Z ])- Positive Lookahead - checks for 0 or more of any characters which are not)followed by a space or a letter[^)]+?- Captures 1 or more characters which are not)\)- Finally matches the closing ParanthesisExplanation(for 2nd Regex)
\(- matches opening paranthesis(?!\d+\))- Negative Lookahead - matches only those strings which do not have ALL the characters as digits after the opening paranthesis but before the closing paranthesis appears[^)]+?- Captures 1 or more characters which are not)\)- Finally matches the closing ParanthesisNow, you can try your Replace statement as:
OR
str = str.replaceAll("\((?!\d+\))[^)]+?\)","");