如何使用String.split()按正则分割字符串并排除特定子串、去除空元素?
Fixing the Split to Preserve
ORDER_ITEMS->TOTAL_QTY and Remove Empty Elements Got it, let's tackle this split problem you're facing. The issue with your current regex is that it treats - and > as separate delimiters, which breaks ORDER_ITEMS->TOTAL_QTY into two parts, plus it generates empty strings from consecutive delimiters (like parentheses and spaces next to each other).
Solution Code
Here's how you can adjust your regex and filter out empty strings to get the exact result you want:
import java.util.Arrays; public class SplitExample { public static void main(String[] args) { String expr = "round((TOTAL_QTY * 100) / SUM(ORDER_ITEMS->TOTAL_QTY) , 1)"; // Regex to split on delimiters but preserve "->" String regex = "[\\s()*+\\/^!@#%&]|-(?!>)|(?<!-)>"; String[] tokens = expr.split(regex); // Filter out empty strings from the result tokens = Arrays.stream(tokens).filter(s -> !s.isEmpty()).toArray(String[]::new); // Print the result to verify System.out.println(Arrays.toString(tokens)); // Output: [round, TOTAL_QTY, 100, SUM, ORDER_ITEMS->TOTAL_QTY, 1] } }
How the Regex Works
Let's break down the regex [\\s()*+\\/^!@#%&]|-(?!>)|(?<!-)>:
[\\s()*+\\/^!@#%&]: Matches whitespace, parentheses, and all your target operators (except-and>that form->). These are standard delimiters we want to split on.-(?!>): Matches a-only if it's not followed by a>(so we don't split the->in your identifier).(?<!-)>: Matches a>only if it's not preceded by a-(again, preserving the->pair).
Why This Fixes Your Problem
- Your original regex treated every
-and>as a delimiter, which splitORDER_ITEMS->TOTAL_QTYinto separate elements. This new regex skips splitting when-and>are paired together. - The
filterstep removes any empty strings created by consecutive delimiters (like((which would split into an empty string between the two parentheses).
内容的提问来源于stack exchange,提问作者a.toraby
相关产品推荐
相关产品推荐

