模式匹配以匹配最长的子字符串

时间:2018-09-15 18:47:40

标签: java regex matcher

我有这个正则表达式D+U

它应与以下字符串UDDDUDUU匹配一次,但对于Java,它匹配3次。它与DDDU DU相匹配。我正在使用https://regex101.com/检查我的正则表达式,它应该只匹配一次,即DDDU

我正在尝试解决这一HackerRank的挑战。我还尝试使用Pattern's,因为我想练习使用这些类。

我到底在做什么错?

这是我的代码:

static int match(int n, String s) {
    Matcher matcher = Pattern.compile("D+U").matcher(s);
    int count = 0;
    int i = 0;
    while (matcher.find(i)) {
        count++;
        i = matcher.end() + 1;
    }
    return count;
}

1 个答案:

答案 0 :(得分:0)

正则表达式+与一个或多个前面的字符/正则表达式匹配。因此,这将匹配DU的任何序列。

如果您想返回最长的匹配项,可以这样做:

static String match(String s) {
    ArrayList<String> matches = new ArrayList<>();
    Matcher matcher = Pattern.compile("D+U").matcher(s);
    int i = 0;
    while (matcher.find(i)) {
       matches.add(matcher.group());
       i = matcher.end();
    }   
    return Collections.max(matches, Comparator.comparing(c -> c.length()));
}

哪个(使用UDDDUDUU测试用例)返回DDDU。还请注意,由于您从未使用过n参数,因此我将其删除