繁体   English   中英

Java 正则表达式模式和匹配器问题

[英]Java regex Pattern and Matcher question for

假设我有一个 15 行的字符串,如下所示(左数字不是字符串的一部分)

 1. Score 2
 2. Score 3
 3. not score 2
 4. score 3
 5. score 2
 6. not score 3
 7. score 3
 8. not score 2
 9. score 3
 10. not score 3
 11. score 2
 12. not score 3
 13. not score 2
 14. score 2
 15. not score 3

我想编写一个程序,告诉我最后十行中有多少个“分数 3”。 所以从1-10。 请帮忙

            Pattern w1 = Pattern.compile("score 3");
            Pattern l1 = Pattern.compile("score 2");
            Matcher m1 = w1.matcher( example );
            Matcher s1 = l1.matcher( example);
            while (m1.find()) {
                score3++; }
            while (s1.find()) {
                score2++; } } }

正如评论中指出的那样,您不需要正则表达式来实现您所需要的。 实际上,如果您需要计算最后十行中与“分数 3”完全对应的行数,那么您只需要使用equals方法:

String s = "Score 2\n" +
        "Score 3\n" +
        "not score 2\n" +
        "score 3\n" +
        "score 2\n" +
        "not score 3\n" +
        "score 3\n" +
        "not score 2\n" +
        "score 3\n" +
        "not score 3\n" +
        "score 2\n" +
        "not score 3\n" +
        "not score 2\n" +
        "score 2\n" +
        "not score 3";

String[] vetRows = s.split("\\n");
long countEquals = IntStream.range(vetRows.length - 10, vetRows.length).
        filter(i -> vetRows[i].equals("score 3"))
        .count();

相反,如果您需要计算最后 10 行中包含“分数 3”的出现次数,那么contains方法就是您所需要的:

String s = "Score 2\n" +
        "Score 3\n" +
        "not score 2\n" +
        "score 3\n" +
        "score 2\n" +
        "not score 3\n" +
        "score 3\n" +
        "not score 2\n" +
        "score 3\n" +
        "not score 3\n" +
        "score 2\n" +
        "not score 3\n" +
        "not score 2\n" +
        "score 2\n" +
        "not score 3";

long countContains = IntStream.range(vetRows.length - 10, vetRows.length)
        .filter(i -> vetRows[i].contains("score 3"))
        .count();

这里还有一个测试代码的链接:

https://www.jdoodle.com/iembed/v0/ry5

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM