You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用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 split ORDER_ITEMS->TOTAL_QTY into separate elements. This new regex skips splitting when - and > are paired together.
  • The filter step removes any empty strings created by consecutive delimiters (like (( which would split into an empty string between the two parentheses).

内容的提问来源于stack exchange,提问作者a.toraby

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 10:57:31