遍历字符串并检查是否满足某些条件

looping through a string and checking if certain conditions are met

我需要编写一段代码,它接受一个输入字符串参数,并确定每对加起来为 10 的数字之间是否恰好存在 3 个问号。如果是,则 return 为真,否则 return false.Some 示例测试用例如下

"arrb6???4xxbl5???eee5"      => true
"acc?7??sss?3rr1??????5"     => true
"5??aaaaaaaaaaaaaaaaaaa?5?5" => false
"9???1???9???1???9"          => true
"aa6?9"                      => false

我已经尝试在 Java 中实现它,如下所示,但结果不如预期

public static String QuestionsMarks(String str) { 
str = str.replaceAll("[a-z]+","");
Pattern pattern = Pattern.compile("([0-9])([?])([?])([0-9])");
Pattern pattern01 = Pattern.compile("([0-9])([?])([?])([0-9])");
Matcher matcher01 = pattern01.matcher(str);
Pattern pattern02 = Pattern.compile("([0-9])([0-9])");
Matcher matcher02 = pattern02.matcher(str);
Matcher matcher = pattern.matcher(str);

if (matcher01.find() || matcher02.find()) {
return "false";
} else if (matcher.find()) {
  return "true";
 }

return "false";
}

检测以问号分隔的重叠数字的正则表达式如下:

(?=((\d)([^?\d]*\?[^?\d]*)*(\d))) 它使用正前瞻 (?=) 来处理此模式的相邻匹配项之间的重叠数字:
(\d)([^?\d]*\?[^?\d]*)*(\d): 由任意数量的问号和其他可选字符分隔的两个数字。

Online demo of the regexp

因此,正则表达式提供了以下形式的匹配流:Group1=StringWithQuestionMarks, Group2=Digit, Group4=Digit 应根据规则对其进行验证:将数字总和计算为 10,并将数字之间的问号计算为 3 .

使用 Stream 的示例实现 API:

private static final Pattern DIGS = Pattern.compile("(?=((\d)([^?\d]*\?[^?\d]*)*(\d)))");

public static boolean hasTotal10Around3QMarks(String str) {
    
    Supplier<Stream<MatchResult>> ss = () -> DIGS
        .matcher(str)
        .results()
        .filter(r -> r.groupCount() == 4 
            && 10 == Integer.parseInt(r.group(2)) + Integer.parseInt(r.group(4))
        );
    
    return ss.get().findAny().isPresent() &&
           ss.get().allMatch(r -> 3 == r.group(1).chars()
                                                 .filter(c -> c == '?')
                                                 .count()
    );
}

Supplier<Stream> 有助于重用 MatchResult 的流来处理最后一个测试用例,当没有匹配的数字对时,空流 allMatch 之间有 3 个问号 returns true).

测试:

String[] tests = {
    "arrb6???4xxbl5???eee5",
    "acc?7??sss?3rr1??????5",
    "5??aaaaaaaaaaaaaaaaaaa?5?5",
    "9???1???9???1???9",
    "aa6?9",
    ""
};

Arrays.stream(tests)
      .forEach(t -> System.out.printf("'%s' => %s%n", t, hasTotal10Around3QMarks(t)));

输出:

'arrb6???4xxbl5???eee5' => true
'acc?7??sss?3rr1??????5' => true
'5??aaaaaaaaaaaaaaaaaaa?5?5' => false
'9???1???9???1???9' => true
'aa6?9' => false
'' => false