Assuming there are no nested parentheses, you can do this by removing the character sequences you don't need. The character sequences you don't need are:
- Any sequence starting with
(
and ending with )
;
- Any other character that isn't an operator.
You can throw out all those sequences using replaceAll
. This statement will set operators
to a string with all those removed, i.e. "*+/-+"
:
operators = inputString.replaceAll("\\([^)]*\\)|[^-+*/]", "");
This causes any sequence composed of a (
, followed by zero or more non-)
characters, followed by )
to be replaced with ""
; it also causes any character that is not -
, +
, *
, or /
, to be replaced with ""
. The first alternative is tested first, so the second one will only affect characters that aren't in parentheses. Note that the hyphen in [^-+*/]
comes first, before any other characters, so that the -
isn't interpreted as indicating a range of characters.
If nested parentheses are a possibility, then don't use regexes. Regexes in Java cannot handle nested constructs. (I think there are some languages that support regex features that do handle them, but not Java. At least not the standard Java runtime. There could be a third-party Java library somewhere that supports it.) azurefrog's answer is the best approach.
Note: Now tested.