首页 > 解决方案 > 使用特殊字符拆分字符串并保留它们

问题描述

我正在尝试使用特殊字符拆分字符串,但无法正确拆分括号。这是我正在尝试的代码:

class Ione
{
    public static void main (String[] args) throws java.lang.Exception
    {
        String str = "g, i+, w+ | (d | (u+, f))+"; 
        String[] chunks = str.split(",\\s+|(?=\\W)");
        for(int q=0; q<chunks.length; q++) {
          System.out.println(""+chunks[q]);   
       } 
    }
}

正则表达式不拆分起始括号(

我正在尝试获得以下输出:

g,i,+,w,+,|,(,d,|,(,u,+,f,),),+

有人可以帮助我。谢谢你。

代码的输出

标签: javaregex

解决方案


所以你想用来split()分别获取每个字符,除了空格和逗号,所以用空格/逗号和“无”分割,即非空格/逗号字符之间的零宽度“空格”。

String str = "g, i+, w+ | (d | (u+, f))+";
String[] chunks = str.split("[\\s,]+|(?<![\\s,])(?![\\s,])");
System.out.println(String.join(",", chunks));

输出

g,i,+,w,+,|,(,d,|,(,u,+,f,),),+

替代方案:搜索您想要的内容,并将其收集到一个数组中或List (需要 Java 9)

String str = "g, i+, w+ | (d | (u+, f))+";
String[] chunks = Pattern.compile("[^\\s,]").matcher(str).results()
        .map(MatchResult::group).toArray(String[]::new);
System.out.println(String.join(",", chunks));

相同的输出。

对于旧版本的 Java,请使用find()循环:

String str = "g, i+, w+ | (d | (u+, f))+";
List<String> chunkList = new ArrayList<>();
for (Matcher m = Pattern.compile("[^\\s,]").matcher(str); m.find(); )
    chunkList.add(m.group());
System.out.println(chunkList);

输出

[g, i, +, w, +, |, (, d, |, (, u, +, f, ), ), +]

您始终可以将 转换List为数组:

String[] chunks = chunkList.toArray(new String[0]);

推荐阅读