A
A
avgwowenjoyer2022-04-04 14:20:37
Java
avgwowenjoyer, 2022-04-04 14:20:37

How to find the number of occurrences of characters from a regular expression in a string?

Regular expression - "\\W | _"(any character except alphabetic and numeric).
You need to count the number of such characters in a string.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
askalidov, 2022-04-04
@avgwowenjoyer

You have an error in the regular expression, parentheses are needed here:

String st = "q!w_e*"
Pattern pattern = Pattern.compile("(\\W)|(_)");
Matcher matcher = pattern.matcher(st);
long matches = matcher.results().count();
System.out.println(matches);

The output, respectively, in this example is 3

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question