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

利用正则表达式

@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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值