How to Match a Pattern in a String in C++?
Last Updated :
04 Mar, 2024
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++
#include <iostream>
#include <regex>
#include <string>
using namespace std;
int main()
{
string text = "GeeksForGeeks" ;
regex pattern(
"(Geek)(.*)" );
if (regex_match(text, pattern)) {
cout << "Pattern found!" << endl;
}
else {
cout << "Pattern not found!" << endl;
}
return 0;
}
|
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.
Share your thoughts in the comments
Please Login to comment...