我想将字符串拆分为括号( [] 和 () ),但是我没有找到好的解决方案。 将它们拆分为“[”和“(”并没有真正的帮助。 基本上我想转
[str1 str2] (str3 str4) hello world
至
- [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));
}
}
}
关于java - 将字符串拆分到括号中,但将它们保留在 Java 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41637936/