Reputation: 3391
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.
Upvotes: 6
Views: 139
Reputation: 5749
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
Upvotes: 2
Reputation: 59986
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 -
:
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)));
Details
\b\w+->\w+\b
to match that special case of ORDER_ITEMS->TOTAL_QTY
|
or\b\w+\b
any other word with word boundariesNote, 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"
Upvotes: 4