VOOZH about

URL: https://www.geeksforgeeks.org/dsa/count-occurrences-of-a-word-in-string-set-2-using-regular-expressions/

⇱ Count occurrences of a word in string | Set 2 (Using Regular Expressions) - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Count occurrences of a word in string | Set 2 (Using Regular Expressions)

Last Updated : 23 Jul, 2025

Given a string str and a word w, the task is to print the number of the occurrence of the given word in the string str using Regular Expression.

Examples:

Input: str = "peter parker picked a peck of pickled peppers”, w = "peck"
Output: 1
Explanation: There is only one occurrence of the word "peck" in the given string. Therefore, the output is 1.

👁 Image

Input: str = "How much wood would a woodchuck chuck if a woodchuck could chuck wood ?", w = "wood"
Output: 2
Explanation: There are only two occurrences of the word "wood" in the given string. 
Therefore, the output is 2.

Input: str = "She sells seashells by the seashore", w = "sea"
Output: 0
Explanation: There is no occurrence of the word "sea" in the given string. Therefore, the output is 0.

Approach: The required regular expression to find the required count of string w in the given string is "\\bw\\b", where \b is a word boundary. Follow the steps to solve the problem

regex = "\\bw\\b"

Below is the implementation of the above approach :


Output
1

Time Complexity : O(N)
Auxiliary Space : O(N)

Comment
Article Tags: