栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Java正则表达式匹配计数

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java正则表达式匹配计数

matcher.find()
找不到所有匹配项,仅找到下一个匹配项。

你必须执行以下操作:

int count = 0;while (matcher.find())    count++;

顺便说一句,

matcher.groupCount()
是完全不同的东西。

完整的例子:

import java.util.regex.*;class Test {    public static void main(String[] args) {        String hello = "HelloxxxHelloxxxHello";        Pattern pattern = Pattern.compile("Hello");        Matcher matcher = pattern.matcher(hello);        int count = 0;        while (matcher.find()) count++;        System.out.println(count);    // prints 3    }}

Handling overlapping matches

当计算上述片段aa中aaaa的时,将为你提供2。

aaaaaa  aa

要获得3个匹配项,即此行为:

aaaaaa aa  aa

你必须在索引处搜索匹配项,

<start of last match> + 1
如下所示:

String hello = "aaaa";Pattern pattern = Pattern.compile("aa");Matcher matcher = pattern.matcher(hello);int count = 0;int i = 0;while (matcher.find(i)) {    count++;    i = matcher.start() + 1;}System.out.println(count);    // prints 3


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/404847.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号