重叠组捕获 [英] Overlapping group capturing

查看:41
本文介绍了重叠组捕获的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请看下面的代码:

public static void main(String[] args) {
    String s = "a < b > c > d";
    String regex = "(\\w\\s*[<>]\\s*\\w)";
    Pattern p = Pattern.compile(regex);
    Matcher m = p.matcher(s);
    int i = 0;
    while (m.find()) System.out.println(m.group(i++));
}

上述程序的输出为:a

但我实际上希望 a <b, b >c、c>d.

我的正则表达式有什么问题吗?

Anything wrong with my regexp here?

推荐答案

试试这个.

    String s = "a < b > c > d";
    String regex = "(?=(\\w{1}\\s{1}[<>]{1}\\s{1}\\w{1})).";
    Pattern p = Pattern.compile(regex);
    Matcher m = p.matcher(s);
    while(m.find()) {
        System.out.println(m.group(1));
    }

更新(基于green的解决方案):

    String s = " something.js > /some/path/to/x19-v1.0.js < y < z < a > b > c > d";
    String regex = "(?=[\\s,;]+|(?<![\\w\\/\\-\\.])([\\w\\/\\-\\.]+\\s*[<>]\\s*[\\w\\/\\-\\.]+))";

    Pattern p = Pattern.compile(regex);
    Matcher m = p.matcher(s);
    while (m.find()) {
        String d = m.group(1);
        if(d != null) {
            System.out.println(d);
        }
    }

这篇关于重叠组捕获的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆