Reputation: 404
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:
@weather in new york and
@order me a pizza
I attempted following: @.+@
but it selects the @
symbol from next match as well.
Upvotes: 0
Views: 1089
Reputation: 27723
Maybe, this simple expression might be close to what you have in mind:
@[^@]*
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.
Upvotes: 2