有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

如何在下一次与Java/Regex匹配之前匹配所有内容?例如,我有一个字符串:

"Check the @weather in new york and @order me a pizza"

我想要两个匹配项:

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

我尝试了以下操作:@.+@但它也从下一个匹配中选择了@符号


共 (1) 个答案

  1. # 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
    

    If you wish to explore/simplify/modify the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.