简体   繁体   中英

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

I have this string:

"round((TOTAL_QTY * 100) / SUM(ORDER_ITEMS->TOTAL_QTY) , 1)"

I tried to split the string using the following code:

String[] tokens = function.split("[ )(*+-/^!@#%&]");

Result is the following array:

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

But I need to split the string as follows:

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

To make it clearer. First of all I need to ignore -> when it splits the string and then remove those empty strings in the result array.

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 eg round((

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

Output:

round
TOTAL_QTY 
100 
SUM
ORDER_ITEMS->TOTAL_QTY 
1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM