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

31 Mar, 2022
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: 1Explanation: There is only one occurrence of the word “peck” in the given string. Therefore, the output is 1.
Input: str = “How much wood would a woodchuck chuck if a woodchuck could chuck wood ?”, w = “wood”Output: 2Explanation: 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: 0Explanation: 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
Create the regular expression pattern for the word w
regex = “\\bw\\b”
Traverse the string, match the regex with the string str using regex_iterator(). Simultaneously, update number of matches. 
Print the total number of matches obtained in the above step.
Below is the implementation of the above approach :
C++
Java
C#
// C++ program for the above approach#include <iostream>#include <regex>using namespace std; // Function to count total occurrences// of word "w" in string "str"void countOccurrences(string str, string w){    // Get the regex to be checked    string regexPattern = "\\b" + w + "\\b";    const regex pattern(regexPattern);     // Variable to count total    // occurrences of the given word    int count = 0;     auto it        = sregex_iterator(str.begin(), str.end(), pattern);     for (it; it != sregex_iterator(); it++) {         // Increment count        count++;    }     // Print the occurrences of the word    cout << count << endl;     return;} // Driver Codeint main(){    // Input    string str        = "peter parker picked a peck of pickled peppers";    string w = "peck";     countOccurrences(str, w);     return 0;}
// Java program for the above approachimport java.util.*;import java.util.regex.*; class GFG {   // Function to count total occurrences  // of word "w" in String "str"  static void countOccurrences(String str, String w)  {         // Get the regex to be checked    String regexPattern = "\\b" + w + "\\b";     Pattern pattern = Pattern.compile(regexPattern);         // Variable to count total    // occurrences of the given word    int count = 0;     while (str.contains(w)) {      str = str.replace(w, "");      // Increment count      count++;    }     // Print the occurrences of the word    System.out.print(count + "\n");     return;  }   // Driver Code  public static void main(String[] args)  {         // Input    String str = "peter parker picked a peck of pickled peppers";    String w = "peck";     countOccurrences(str, w);  }} // This code is contributed by gauravrajput1
// C# program for the above approachusing System;using System.Text.RegularExpressions;public class GFG {   // Function to count total occurrences  // of word "w" in String "str"  static void countOccurrences(String str, String w)  {     // Get the regex to be checked    String regexPattern = "\\b" + w + "\\b";     Regex rx = new Regex(regexPattern,RegexOptions.Compiled | RegexOptions.IgnoreCase);    // Variable to count total    // occurrences of the given word    int count = 0;     while (str.Contains(w)) {      str = str.Replace(w, "");      // Increment count      count++;    }     // Print the occurrences of the word    Console.Write(count + "\n");     return;  }   // Driver Code  public static void Main(String[] args)  {     // Input    String str = "peter parker picked a peck of pickled peppers";    String w = "peck";     countOccurrences(str, w);  }} // This code is contributed by gauravrajput1
1
Time Complexity : O(N)Auxiliary Space : O(N)
GauravRajput1
CPP-regex
regular-expression
Pattern Searching
Strings
Strings
Pattern Searching
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Replace empty Array spaces with numbers [1, 9] such that the other Array is not a Subsequence
How to validate HTML tag using Regular Expression
Check whether two strings contain same characters in same order
How to validate GUID (Globally Unique Identifier) using Regular Expression
Build a DFA to accept Binary strings that starts or ends with "01"
Reverse a string in Java
Write a program to reverse an array or string
C++ Data Types
Longest Common Subsequence | DP-4
Write a program to print all permutations of a given string