[英]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();
這里還有一個測試代碼的鏈接:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.