std regex search in C++
In this article, we will discuss the std::regex_search in C++ with its syntax, and implementation.
Introduction to Regular Expressions:
In order to understand std::regex_search, let's first review regular expressions. Regular expressions are character sequences that specify a search pattern. They are extensively utilized in many different programming languages and tools for text manipulation, validation, and searching.
The header in C++ provides classes and methods for working with regular expressions, hence supporting regular expressions.
Syntax of std::regex_search
We can utilize the std::regex_search function to find a match to a regular expression in a string. It has the following syntax:
template <class charT, class traits>
bool regex_search (const charT* s, const basic_regex<charT,traits>& rgx,
regex_constants::match_flag_type flags = regex_constants::match_default);
Parameters:
- first, last: These are the input iterators, which define the range of characters to search.
- re: It is the regular expression object.
- m: It is a std::match_results object where information about the match will be stored.
- flags: This controls the way that rgx is matched.
Basic Usage
Let's see how we can use the std::regex_search function in C++:
#include <iostream>
#include <regex>
int main() {
auto const regexPattern = std::regex("(my|your) regex");
auto const sampleText1 = std::string("This is a text that includes my regex.");
bool const isPatternInSample1 = std::regex_search(sampleText1, regexPattern);
auto const sampleText2 = std::string("This is a text that includes your regex.");
bool const isPatternInSample2 = std::regex_search(sampleText2, regexPattern);
auto const sampleText3 = std::string("This is a text that includes their regex.");
bool const isPatternInSample3 = std::regex_search(sampleText3, regexPattern);
std::cout <<std::boolalpha
<< "Sample 1 contains the pattern: " << isPatternInSample1 << '\n'
<< "Sample 2 contains the pattern: " << isPatternInSample2 << '\n'
<< "Sample 3 contains the pattern: " << isPatternInSample3 << '\n';
return 0;
}
Output:
![std::regex_search in C++](https://static.tutorialandexample.com/cpp/std-regex-search-in-cpp1.png)
Advanced Usage:
The std::regex_search function provides various options for controlling the search behavior. Some common flags include:
- std::regex_constants::match_default: Default behavior.
- std::regex_constants::match_not_null: Don't match an empty sequence.
- std::regex_constants::match_continuous: Match only at the beginning of the sequence.
- std::regex_constants::match_any: It allows matching anywhere in the sequence.
Moreover, we can use capturing groups to extract specific parts of the matched text. Capturing groups are defined by enclosing part of the regular expression in parentheses.
Example:
Let us take an example to illustrate the std::regex_search() function in C++.
#include <iostream>
#include <regex>
#include <string>
int main() {
std::string text = "Date: 2024-05-08";
std::regex pattern("(\\d{4})-(\\d{2})-(\\d{2})");
std::smatch match;
if (std::regex_search(text, match, pattern)) {
std::cout << "Year: " << match[1] << std::endl;
std::cout << "Month: " << match[2] << std::endl;
std::cout << "Day: " << match[3] << std::endl;
} else {
std::cout << "No match found." << std::endl;
}
return 0;
}
Output:
![std::regex_search in C++](https://static.tutorialandexample.com/cpp/std-regex-search-in-cpp2.png)
Performance Considerations
Despite their strength, regular expressions can be computationally costly, particularly when dealing with complicated patterns and lengthy input strings. Therefore, it is imperative to consider the performance consequences when utilizing regular expressions in performance-critical code.
Search Results and Match Information
Upon successfully locating a match, std::regex_search function adds the match's details to an object called std::match_results. This object includes information on the match's location in the input text and, if the regular expression includes capturing groups, any groups that were captured.
Example:
#include <iostream>
#include <regex>
#include <string>
int main() {
std::string text = "Hello, world!";
std::regex pattern("world");
std::smatch match;
if (std::regex_search(text, match, pattern)) {
std::cout << "Match found at position: " << match.position() << std::endl;
std::cout << "Matched text: " << match.str() << std::endl;
}
return 0;
}
Output:
![std::regex_search in C++](https://static.tutorialandexample.com/cpp/std-regex-search-in-cpp3.png)
Explanation:
In this example, the std::match_results object has methods like prefix() and suffix() to access the text before and after the matched part in addition to position() and str().
Iterating Over Multiple Matches:
The std::regex_search identifies the input string's first match by iterating through multiple matches. Nevertheless, you may use it in conjunction with a loop to locate all matches, moving the search location after each match.
Example:
#include <iostream>
#include <regex>
#include <string>
int main() {
std::string text = "apple banana apple orange apple";
std::regex pattern("apple");
std::smatch match;
while (std::regex_search(text, match, pattern)) {
std::cout << "Found match at position: " << match.position() << std::endl;
text = match.suffix().str(); // Move search position beyond the current match
}
return 0;
}
Output:
![std::regex_search in C++](https://static.tutorialandexample.com/cpp/std-regex-search-in-cpp4.png)
Explanation:
This code snippet demonstrates how to find all occurrences of the word "apple" in a given text.
Non-Greedy Matching:
Regular expressions match as much of the input string as they can by default, which is known as greedy matching. If we want to do non-greedy or lazy matching, we may change this behavior by adding a question mark to quantifiers.
Example:
#include <iostream>
#include <regex>
#include <string>
int main() {
std::string text = "<div>content1</div><div>content2</div>";
std::regex pattern("<div>(.*?)</div>");
std::smatch match;
while (std::regex_search(text, match, pattern)) {
std::cout << "Content: " << match[1] << std::endl;
text = match.suffix().str(); // Move search position beyond the current match
}
return 0;
}
Output:
![std::regex_search in C++](https://static.tutorialandexample.com/cpp/std-regex-search-in-cpp5.png)
Conclusion:
In conclusion, the std::regex_search function offers a robust regular expression-based string search engine. It makes it possible for developers to efficiently complete complex pattern-matching and manipulation tasks. We may take advantage of regular expressions in the C++ programs to the fullest by learning about their syntax and available features. But it's important to think about how performance may be affected, particularly for intricate patterns and lengthy input strings. For C++ text processing and modification, std::regex_search may be a useful tool if used carefully.r.