利用正则表达式
@Test
public void test() {
String regex = "a";
String input = "Java";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(input);
int count = 0;
List<Integer> index = new ArrayList<>();
while (m.find()) {
count++;
System.out.println("Match number: " + count);
System.out.println("start: " + m.start());
System.out.println("end: " + m.end());
index.add(m.start());
}
System.out.println("count: " + count);
System.out.println("index: " + index.toString());
String regexp = "\\bcat\\b";
String str = "catcat cat cattie cat";
Pattern pattern = Pattern.compile(regexp);
Matcher matcher = p.matcher(str);
int total = 0;
while (matcher.find()) {
total++;
}
System.out.println("total: " + total);// 5
}
输出:
Match number: 1
start: 1
end: 2
Match number: 2
start: 3
end: 4
count: 2
index: [1, 3]
total: 5
Process finished with exit code 0