3

How can I extract overlapping matches from an input using String.split()?

For example, if trying to find matches to "aba":

String input = "abababa";
String[] parts = input.split(???);

Expected output:

[aba, aba, aba]
4

3 回答 3

5

String#split不会给你重叠的比赛。因为字符串的特定部分,只会包含在获得的数组的唯一索引中,而不包含在两个索引中。

你应该在这里使用PatternMatcher类。你可以使用这个正则表达式: -

Pattern pattern = Pattern.compile("(?=(aba))");

并使用Matcher#find方法获取所有重叠匹配,并group(1)为其打印。

上面的正则表达式匹配每个空字符串,后面跟着aba,然后只打印第一个捕获的组。现在因为look-ahead零宽度断言,所以它不会消​​耗匹配的字符串。因此,您将获得所有重叠的匹配项。

String input = "abababa";
String patternToFind = "aba";

Pattern pattern = Pattern.compile("(?=" + patternToFind + ")");
Matcher matcher = pattern.matcher(input);

while (matcher.find()) {
    System.out.println(patternToFind + " found at index: " + matcher.start());
}

输出: -

aba found at index: 0
aba found at index: 2
aba found at index: 4
于 2012-12-26T19:07:16.940 回答
3

我会使用 indexOf。

for(int i = text.indexOf(find); i >= 0; i = text.indexOf(find, i + 1))
   System.out.println(find + " found at " + i);
于 2012-12-26T19:28:18.760 回答
0

这不是正确使用split(). 从javadocs

围绕给定正则表达式的匹配拆分此字符串。

在我看来,您不是在尝试拆分字符串,而是在字符串中查找正则表达式的所有匹配项。为此,您必须使用Matcher和一些额外的代码,这些代码在 上循环Matcher以查找所有匹配项,然后创建数组。

于 2012-12-26T19:04:49.937 回答