Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get multiple regex matches in Java?

How can I find all substrings that match a regex in Java? (Similar to Regex.Matches in .Net)

like image 724
ripper234 Avatar asked Aug 12 '09 15:08

ripper234


People also ask

How do I add more than one regex?

You can use alternation (|) operator to combine multiple patterns for your regexp. But in case you have various input and you will have to convert them to instance of Date from a string. Then you must follow in a sequence and validate the input one by one.

What is \\ s+ in regex Java?

The plus sign + is a greedy quantifier, which means one or more times. For example, expression X+ matches one or more X characters. Therefore, the regular expression \s matches a single whitespace character, while \s+ will match one or more whitespace characters.

What is difference between matches () and find () in Java regex?

Difference between matches() and find() in Java RegexThe matches() method returns true If the regular expression matches the whole text. If not, the matches() method returns false. Whereas find() search for the occurrence of the regular expression passes to Pattern.

What does \\ mean in Java regex?

Backslashes in Java. The backslash \ is an escape character in Java Strings. That means backslash has a predefined meaning in Java. You have to use double backslash \\ to define a single backslash. If you want to define \w , then you must be using \\w in your regex.


2 Answers

Create a Matcher and use find() to position it on the next match.

like image 175
Aaron Digulla Avatar answered Oct 27 '22 02:10

Aaron Digulla


Here is a code sample:

int countMatches(Pattern pattern, String str) {
  int matches = 0;
  Matcher matcher = pattern.matcher(str);
  while (matcher.find())
    matches++;
  return matches;
}
like image 34
ripper234 Avatar answered Oct 27 '22 02:10

ripper234