Pepria
Pepria

Reputation: 404

Java/Regex - match everything until next match

How do I match everything till the next match with Java/Regex ? For example, I have the string:

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

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.

Upvotes: 0

Views: 1089

Answers (1)

Emma
Emma

Reputation: 27723

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. If you'd like, you can also watch in this link, how it would match against some sample inputs.


Upvotes: 2

Related Questions