要求:对于一个字符串,根据空格分割成多条字符串,在双括号中的字符串不用分割
示例:
String input="one ((two three)) four"
将被分割成
String[] results={"one","((two three))","four"};
解法:
要使用的正则表达式:\w+|\(\([\w\s]*\)\)
完整的Java类:
class Regex_Split{
publicstaticvoidmain(String[]args){
Stringinput="one ((two three)) four"; //要分割的字符串
String[] results=splitByMatchedGroups(input,"\\w+|\\(\\([\\w\\s]*\\)\\)");
for(Stringresult : results){
System.out.println(arg);
}
}
staticString[]splitByMatchedGroups(String input String patternString){
List<String>matchList=newArrayList<>();
MatcherregexMatcher=Pattern.compile(patternString).matcher(string);
while(regexMatcher.find()){
matchList.add(regexMatcher.group());
}
returnmatchList.toArray(newString[0]);
}