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++;
}
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.
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.
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.
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.
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:
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);
Matcher
in Java 9 provides results()
which returns a Stream<MatchResult>
. So your code becomes
int counter = matcher.results().count();
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With