简体   繁体   English

Java / Regex-匹配所有内容,直到下次匹配

[英]Java/Regex - match everything until next match

How do I match everything till the next match with Java/Regex ? 在下一次与Java / Regex匹配之前,我该如何匹配所有内容? For example, I have the string: 例如,我有字符串:

"Check the @weather in new york and @order me a pizza" “检查纽约的@weather并@命令我披萨”

I want to get two matches: 我想得到两场比赛:

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

I attempted following: @.+@ but it selects the @ symbol from next match as well. 我尝试了以下操作: @.+@但是它也从下一个匹配项中选择了@符号。

Maybe, this simple expression might be close to what you have in mind: 也许,这个简单的表达可能与您的想法很接近:

@[^@]*

Test 测试

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


    }
}

Output 产量

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

If you wish to explore/simplify/modify the expression, it's been explained on the top right panel of regex101.com . 如果您想浏览/简化/修改该表达式,请在regex101.com的右上方面板中进行说明 If you'd like, you can also watch in this link , how it would match against some sample inputs. 如果愿意,您还可以在此链接中观看,它将如何与某些示例输入匹配。


声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM