【问题标题】:Java regular expression with lookahead具有前瞻功能的 Java 正则表达式
【发布时间】:2011-07-28 06:37:23
【问题描述】:

有没有办法在 java 中打印出正则表达式模式的前瞻部分?

    String test = "hello world this is example";
    Pattern p = Pattern.compile("\\w+\\s(?=\\w+)");
    Matcher m = p.matcher(test);
    while(m.find())
        System.out.println(m.group());

这个 sn-p 打印出来:

你好
世界


我想要做的是成对打印单词:

你好世界
世界这个
这个 是
是例子

我该怎么做?

【问题讨论】:

    标签: java regex pattern-matching regex-lookarounds


    【解决方案1】:

    您可以简单地将捕获括号放在前瞻表达式中:

    String test = "hello world this is example";
    Pattern p = Pattern.compile("\\w+\\s(?=(\\w+))");
    Matcher m = p.matcher(test);
    while(m.find()) 
        System.out.println(m.group() + m.group(1));
    

    【讨论】:

    • 不错。我打算在不更改 Java 代码的情况下建议 \w+\s(?=(\w+))\1,但这会消耗捕获组...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-22
    • 2012-12-07
    • 1970-01-01
    • 1970-01-01
    • 2015-09-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多