正则表达式统计字符串中字符、字符串重复次数

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhoukikoo/article/details/79422431

利用正则表达式

@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

猜你喜欢

转载自blog.csdn.net/zhoukikoo/article/details/79422431