java 正则表达式3

论坛 期权论坛 脚本     
匿名技术用户   2020-12-28 04:41   32   0

问题: 匹配"联想 昭阳e280l"之中的"邵阳" (其中联想 邵阳之间含有(0-n个)空格)。

解决方案:

public class Question {
    public static void main(String[] args) {
        String regex="联想    昭阳e280l";
        Pattern p=Pattern.compile("(?<=联想)\\s*([\u4e00-\u9fa5]*)\\w*");
        Matcher m=p.matcher(regex);
        System.out.println(m.find());
        System.out.println(m.group(1));
    }
}

说明:

(?<=exp)也叫零宽度正回顾后发断言,它断言自身出现的位置的前面能匹配表达
式exp。比如(?<=\bre)\w+\b会匹配以re开头的单词的后半部分(除了re以外的部分),

例如在查找reading a book时,它匹配ading

另外一种类似的匹配方式,本质上与上面一样。贴出代码只是想说说明分组的相关问题。

public static void main(String[] args) {
        String regex="联想昭阳e280l";
        // (联想)为第一组     ([\\u4e00-\\u9fa5]*)为第二组
        Pattern p=Pattern.compile("(?<=(联想))\\s*([\\u4e00-\\u9fa5]*)(?=\\w+)");
        Matcher m=p.matcher(regex);
        while(m.find()){
            int groupCount=m.groupCount();
            System.out.println("groupCount:"+groupCount+"-->"+ m.group());
            for(int i=1;i<=groupCount;i++){
                System.out.println(m.group(i));
            }
        }
    }

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:7942463
帖子:1588486
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP