Open In App

How to Match a Pattern in a String in C++?

Last Updated : 04 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, strings are sequences of characters stored in a char array. Matching a pattern in a string involves searching for a specific sequence of characters (the pattern) within a given string. In this article, we will learn how to match a pattern in a string in C++.

Example:

Input:
Text: "GeeksForGeeks"
Pattern: "(Geek)(.*)" // Geek followed by any character

Output:
Pattern matched!

Pattern Matching in C++

To match a pattern in a string we can use regular expressions, which provide a powerful and flexible way to describe and match patterns within strings. C++ provides the <regex> library, which offers support for regular expressions, allowing for more complex pattern matching.

Approach:

  • Use the std::regex class to create a regular expression object, passing the pattern as a parameter to the constructor.
  • Use std::regex_search or std::regex_match to search for or match the pattern within the string.
  • If a match is found print pattern matched.

C++ Program to Match a Pattern in a String

The below program demonstrates how we can match a pattern in a string in C++.

C++




// C++ Program to show how to match a pattern in a string
#include <iostream>
#include <regex>
#include <string>
using namespace std;
  
int main()
{
    string text = "GeeksForGeeks";
  
    // Define the regular expression pattern to match
    regex pattern(
        "(Geek)(.*)"); // Geek followed by any character
  
    // Check if the entire string matches the pattern
    if (regex_match(text, pattern)) {
        // If matched, print message
        cout << "Pattern found!" << endl;
    }
    else {
        // If not matched, print message
        cout << "Pattern not found!" << endl;
    }
  
    return 0;
}


Output

Pattern found!

Time Complexity: O(N), here N is the size of the input string.
Auxiliary Space: O(1)

Note: For larger texts or more complex patterns, consider using more efficient string matching algorithms like the Knuth-Morris-Pratt (KMP) algorithm or the Boyer-Moore algorithm. These algorithms can handle larger inputs more effectively.


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads