【问题标题】:Java/Regex - match everything until next matchJava/Regex - 匹配所有内容直到下一次匹配
【发布时间】:2019-08-24 18:40:08
【问题描述】:

如何匹配所有内容,直到下一次与 Java/Regex 匹配?例如,我有字符串:

“查看@weather in new york 并@order me a Pizza”

我想要两场比赛:

  1. @weather in new york and
  2. @order me a pizza

我尝试关注:@.+@,但它也会从下一个匹配项中选择 @ 符号。

【问题讨论】:

  • 提前查找最后一个@,或使用[^@]+
  • 只是一个想法,但非贪婪的运算符也不能工作吗? @.+?
  • 群组仅用于此目的:(@[^@]+?)(@.+)$

标签: java regex


【解决方案1】:

也许,这个简单的表达方式可能与您的想法很接近:

@[^@]*

测试

import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class re{
    public static void main(String[] args){
        final String regex = "@[^@]*";
        final String string = "Check the @weather in new york and @order me a pizza";

        final Pattern pattern = Pattern.compile(regex);
        final Matcher matcher = pattern.matcher(string);

        while (matcher.find()) {
            System.out.println("Full match: " + matcher.group(0));
            for (int i = 1; i <= matcher.groupCount(); i++) {
                System.out.println("Group " + i + ": " + matcher.group(i));
            }
        }


    }
}

输出

Full match: @weather in new york and 
Full match: @order me a pizza

如果您想探索/简化/修改表达式,它已经 在右上角的面板上进行了解释 regex101.com。如果你愿意,你 也可以在this link看,怎么搭配 针对一些样本输入。


【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多