繁体   English   中英

如何根据括号拆分字符串并避免空格

[英]How to split a string based on parenthesis and avoiding whitespace

我正在尝试使用字符串上的 str.split() 重新格式化字符串,例如

“(ABD)(DEFG)(HIJKLMN)”(之间有一个或多个空格)

我试过使用这个 RegEx (Java)

[the example string] .split("\\(|\\)")

我的 output 一直在我的数组中包含“”或“”以防止拆分,我不希望我希望我的数组是这样的

数组[0] = "ABC" 数组[1] = "DEFG" 等等。

我将执行两个步骤,使用String.replaceAll(String, String)删除()字符。 然后,在空白处拆分。 喜欢,

String str = "(ABD) (DEFG) (HIJKLMN)";
System.out.println(Arrays.toString(str.replaceAll("[()]", "").split("\\W+")));

哪个输出(根据要求)

[ABD, DEFG, HIJKLMN]

或者,您可以使用ArrayList并编译可重用Pattern以对()文字的内容执行分组操作。 喜欢,

String str = "(ABD) (DEFG) (HIJKLMN)";
Pattern p = Pattern.compile("\\((\\w+)\\)");
Matcher m = p.matcher(str);
List<String> matches = new ArrayList<>();
while (m.find()) {
    matches.add(m.group(1));
}
System.out.println(matches);

它将继续在输入() (s)之间没有空格的情况下工作,如String str = "(ABD)(DEFG)(HIJKLMN)";

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM