将字符串拆分为括号,但将其保留在Java中

将字符串拆分为括号,但将其保留在Java中,java,split,Java,Split,我想将字符串拆分为方括号([]和()),但我没有找到一个好的解决方案。 将它们拆分为“[”和“(”并没有真正的帮助。 基本上我想转身 [str1 str2] (str3 str4) hello world 到 编辑: 我现在有这个正则表达式:\s+(?![^[][*]] 但我似乎无法添加()(它忽略了[]中的内容) 编辑2: 标记为重复。我的问题是将括号中的字符串放在一起,而不是按符号拆分。这会让您接近(它匹配方括号和括号中的字符串,但不匹配末尾的“hello world”: import j

我想将字符串拆分为方括号([]和()),但我没有找到一个好的解决方案。 将它们拆分为“[”和“(”并没有真正的帮助。 基本上我想转身

[str1 str2] (str3 str4) hello world

编辑:

我现在有这个正则表达式:\s+(?![^[][*]] 但我似乎无法添加()(它忽略了[]中的内容)

编辑2:

标记为重复。我的问题是将括号中的字符串放在一起,而不是按符号拆分。

这会让您接近(它匹配方括号和括号中的字符串,但不匹配末尾的“hello world”:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SplitRegex {

    public static void main(String[] args) {
        // The search string
        String str = "[str1 str2] (str3 str4) hello world";

        // The Regular expression (Finds [(word)] tokens)
        Pattern pt = Pattern.compile("[\\(\\[]([^\\]\\)]*)[\\]\\)]");

        // Match the string with the pattern
        Matcher m = pt.matcher(str);

        // If results are found
        while (m.find()) {
            System.out.println(m.group(0)); 
        }
    }

}
这使您接近(它匹配方括号和圆括号内的字符串,但不匹配末尾的“hello world”:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SplitRegex {

    public static void main(String[] args) {
        // The search string
        String str = "[str1 str2] (str3 str4) hello world";

        // The Regular expression (Finds [(word)] tokens)
        Pattern pt = Pattern.compile("[\\(\\[]([^\\]\\)]*)[\\]\\)]");

        // Match the string with the pattern
        Matcher m = pt.matcher(str);

        // If results are found
        while (m.find()) {
            System.out.println(m.group(0)); 
        }
    }

}

下面是另一个更紧凑的解决方案:

String str = "[str1 str2] (str3 str4) hello world";
String[] seperatedWords = str.split("\\r+(?:\\(.*\\))|(?:[.*])");

下面是另一个更紧凑的解决方案:

String str = "[str1 str2] (str3 str4) hello world";
String[] seperatedWords = str.split("\\r+(?:\\(.*\\))|(?:[.*])");

如果您有[[str1 str2]strA](str3 str4)??String::split(regex)?@ΦXocę웃Пepeúpaツ 应该是“[[str1 str2]strA]”和“(str3 str4)”。但我不允许使用这种字符串。@CraigR8806我对正则表达式没有太多经验:l@CraigR8806是的,我知道这很混乱而且不是一个有效的方法。但是如果[]或()只出现一次,那么它值得一试。如果你有[[str1 str2]strA](str3 str4)??String::split(regex)?@ΦXocę웃Пepeúpaツ 应该是“[[str1 str2]strA]”和“(str3 str4)”。但我不允许使用这种字符串。@CraigR8806我对正则表达式没有太多经验:l@CraigR8806是的,我知道它很凌乱而且效率不高。但是如果[]或()只出现一次,那么它值得一试。谢谢!必须重写一点,而且效果很好!再次感谢!)谢谢!不得不重写一下,效果很好!再次感谢!:)