Saturday, September 6, 2025
HomeLanguagesJavaCount Occurrences of a Given Character using Regex in Java

Count Occurrences of a Given Character using Regex in Java

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));
    }
}


Output

The occurrence of e in neveropen is 4

Related Article: 

RELATED ARTICLES

Most Popular

Dominic
32270 POSTS0 COMMENTS
Milvus
82 POSTS0 COMMENTS
Nango Kala
6639 POSTS0 COMMENTS
Nicole Veronica
11803 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11869 POSTS0 COMMENTS
Shaida Kate Naidoo
6752 POSTS0 COMMENTS
Ted Musemwa
7029 POSTS0 COMMENTS
Thapelo Manthata
6705 POSTS0 COMMENTS
Umr Jansen
6721 POSTS0 COMMENTS