Say I have a string with 15 rows kind of like the following (left numbers not part of the string)
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
I want to write a program that tells me how many how many "score 3" 's there are in the last ten rows. so from 1-10. Pls help
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++; } } }
As it has been pointed out in the comments you don't need regex to achieve what you need. In fact, if you need to count the number of rows that exactly correspond to "score 3" within your last ten rows, then you just need to use the equals
method:
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();
Instead, if you need to count the occurrences that contain "score 3" within the last 10 rows, then the contains
method is what you need:
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();
Here there is also a link to test the code:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.