Using String.split() How can I split a string based on a regular expression excluding a certain string

Solution 1

Ok, I think you can do it in two steps, replace all non necessary characters with space for example and then split with space, your regex can look like like :

[)(*+/^!@#%&,]|\\b-\\b

Your code :

String[] tokens = function.replaceAll("[)(*+/^!@#%&,]|\\b-\\b", " ").split("\\s+");

Note that I used \\b-\\b to replace only - :

Solution 2

Or If you want something clean, you can use Pattern with Matcher like this :

Pattern.compile("\\b\\w+->\\w+\\b|\\b\\w+\\b")
        .matcher("round((TOTAL_QTY * 100) / SUM(ORDER_ITEMS->TOTAL_QTY) , 1)")
        .results()
        .map(MatchResult::group)
        .forEach(s -> System.out.println(String.format("\"%s\"", s)));

regex demo

Details

  • \b\w+->\w+\b to match that special case of ORDER_ITEMS->TOTAL_QTY
  • | or
  • \b\w+\b any other word with word boundaries

Note, this solution work from Java9+, but you can use a simple Pattern and Matcher solution.

Outputs

"round"
"TOTAL_QTY"
"100"
"SUM"
"ORDER_ITEMS->TOTAL_QTY"
"1"

Could see a couple of very good solutions provide by YCF_L

Here is one more solution:

String[] tokens = function.replace(")","").split("\\(+|\\*|/|,");

Explanation:

\\(+ Will split by ( and + will ensure that multiple open bracket cases and handled e.g. round((

|\\*|/|, OR split by * OR split by / OR split by ,

Output:

round
TOTAL_QTY 
100 
SUM
ORDER_ITEMS->TOTAL_QTY 
1

Tags:

Java

Split

Regex