Skip to content
Related Articles

Related Articles

Count occurrences of a given character using Regex in Java
  • Difficulty Level : Basic
  • Last Updated : 30 May, 2019

Given a string and a character, the task is to make a function which counts the occurrence of the given character in the string using ReGex.


Input: str = "geeksforgeeks", c = 'e'
Output: 4
'e' appears four times in str.

Input: str = "abccdefgaa", c = 'a' 
Output: 3
'a' appears three times in str.


  • 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 occurrences, increment the counter by 1

Below is the implementation of the above approach:

// 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))
        int res = 0;
        // for every presence of character ch
        // increment the counter res by 1
        while (matcher.find()) {
        return res;
    // Driver method
    public static void main(String args[])
        String str = "geeksforgeeks";
        char c = 'e';
        System.out.println(count(str, c));



Related Article:

Recommended Articles
Page :