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

问题描述 投票:0回答:1

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

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

我正在努力解决这个HackerRank挑战。我也在尝试使用Pattern,因为我想练习使用这些类。

我究竟做错了什么?

这是我的代码:

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;
}
java regex matcher
1个回答
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的参数,因为您从未使用它

© www.soinside.com 2019 - 2024. All rights reserved.