我的目标是在找到模式时给出一个字符串,然后将它们添加到单独的数组中。
例如
我的测试字符串是String input = "this is a sentence continents=Asia end continents=Europe end continents=Africa end continents=Australia end continents=South America end continents=North America end continents=Antartica end";
结果是[continents, Asia, continents, Europe, continents, Africa, continents, Australia, continents, South America, continents, North America]
我想要的是将它们添加到单独的数组中,如下所示[continents, Asia], [continents, Europe], [continents, Africa], [continents, Australia], [continents, South America], [continents, North America], [continents, Antartica]
以下是我的代码:
list = new ArrayList<>();
Pattern pattern = Pattern.compile("continents=(.+?) end ");
Matcher matcher = pattern.matcher(input);
while (matcher.find()) {
list.add("continents");
value = matcher.group(1);
list.add(value);
}
任何帮助将不胜感激。谢谢!
最佳答案
如果我正确理解了您的问题,那么您就快到了。您只需要将每个匹配项添加到不同的列表中,然后将该列表添加到外部列表中:
List<List<String>> list = new ArrayList<>();
Pattern pattern = Pattern.compile("continents=(.+?) end ");
Matcher matcher = pattern.matcher(input);
while (matcher.find()) {
List<String> innerList = new ArrayList<>();
innerList.add("continents");
String value = matcher.group(1);
innerList.add(value);
list.add(innerList);
}