我正在尝试使用str.split()重新格式化字符串,例如
“(ABD)(DEFG)(HIJKLMN)”(之间有一个或多个空格)
我尝试使用此RegEx(Java)
[the example string] .split("\\(|\\)")
我的输出一直保持数组中不包含“”或“”,这是我不希望的,因为我不希望我的数组是这样的
array [0] =“ ABC” array [1] =“ DEFG” 等
答案 0 :(得分:4)
我将执行两个步骤,使用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);
它将在输入面对()
之类的String str = "(ABD)(DEFG)(HIJKLMN)";
时保持空白,