Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java regex - one liner for counting matches

Tags:

Is there a one liner to replace the while loop?

String formatSpecifier = "%(\\d+\\$)?([-#+ 0,(\\<]*)?(\\d+)?(\\.\\d+)?([tT])?([a-zA-Z%])";
Pattern pattern = Pattern.compile(formatSpecifier);
Matcher matcher = pattern.matcher("hello %s my name is %s");

// CAN BELOW BE REPLACED WITH A ONE LINER?
int counter = 0;
while (matcher.find()) {
    counter++;
}
like image 689
Jenna Kwon Avatar asked Sep 05 '17 05:09

Jenna Kwon


People also ask

How do you count matches in a regular expression?

To count the number of regex matches, call the match() method on the string, passing it the regular expression as a parameter, e.g. (str. match(/[a-z]/g) || []). length . The match method returns an array of the regex matches or null if there are no matches found.

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.

What does 1 mean in regex in Java?

It indicates a specific number, lists of numbers, or range (to infinity). A number indicates an exact number of occurrences. The coma is used to indicate multiple (when between numbers) or a range to infinity (when not followed by a number.

How do you match numbers in Java?

Matching Digits You can match digits of a number with the predefined character class with the code \d . The digit character class corresponds to the character class [0-9] . Since the \ character is also an escape character in Java, you need two backslashes in the Java string to get a \d in the regular expression.


1 Answers

Personally I don't see any reason to aim for one-liner given the original code is already easy to understand. Anyway, several ways if you insists:

1. Make a helper method

make something like this

static int countMatches(Matcher matcher) {
  int counter = 0;
  while (matcher.find())
    counter++;
  return counter;
}

so your code become

int counter = countMatches(matcher);

2. Java 9

Matcher in Java 9 provides results() which returns a Stream<MatchResult>. So your code becomes

int counter = matcher.results().count();

3. String Replace

Similar to what the other answer suggest.

Here I am replacing with null character (which is almost not used in any normal string), and do the counting by split:

Your code become:

int counter = matcher.replaceAll("\0").split("\0", -1).length - 1;
like image 86
Adrian Shum Avatar answered Oct 13 '22 13:10

Adrian Shum