Given a string and a character, the task is to make a function that counts the occurrence of the given character in the string using Regex.
Examples:
Input: str = "neveropen", c = 'e' Output: 4 'e' appears four times in str. Input: str = "abccdefgaa", c = 'a' Output: 3 'a' appears three times in str.
Regular Expressions
Regular Expressions or Regex is an API for defining String patterns that can be used for searching, manipulating, and editing a string in Java. Email validation and passwords are a few areas of strings where Regex is widely used to define the constraints. Regular Expressions are provided under java.util.regex package.
Approach – Using Matcher.find() method in Java Regex
- Get the String in which it is to be matched
- Find all occurrences of the given character using Matcher.find() function (in Java)
- For each found occurrence, increment the counter by 1
Below is the implementation of the above approach:
Java
// Java program to count occurrences // of a character using Regex import java.util.regex.*; class GFG { // Method that returns the count of the given // character in the string public static long count(String s, char ch) { // Use Matcher class of java.util.regex // to match the character Matcher matcher = Pattern.compile(String.valueOf(ch)) .matcher(s); int res = 0 ; // for every presence of character ch // increment the counter res by 1 while (matcher.find()) { res++; } return res; } // Driver method public static void main(String args[]) { String str = "neveropen" ; char c = 'e' ; System.out.println( "The occurrence of " + c + " in " + str + " is " + count(str, c)); } } |
The occurrence of e in neveropen is 4
Related Article: