具有前瞻功能的 Java 正则表达式

发布于 2024-10-30 13:49:10 字数 437 浏览 6 评论 0原文

有没有办法在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());

这段代码打印出来:

你好
世界
这是

我想要做的是将单词作为对打印:

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

我该怎么做?

is there a way to print out lookahead portion of a regex pattern in 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());

this snippet prints out :

hello
world
this
is

what I want to do is printing the words as pairs :

hello world
world this
this
is
is example

how can I do that?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

浅忆流年 2024-11-06 13:49:10

您可以简单地将捕获括号放在先行表达式内:

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));

You can simply put capturing parentheses inside the lookahead expression:

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));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文