This tutorial will discuss about a unique way to check if any element in array matches regex pattern in C++.
The std::regex_match()
function from the <regex>
header file, accepts a string as the first argument and a regex pattern as the second argument. It returns true
if the given string matches the given regex pattern.
Now, to check if all string elements of an array matches a given regex pattern, we can use the STL Algorithm std::any_of()
.
The std::any_of()
function accepts the start and end iterators of array as first two arguments. As the third argument, we will pass a Lambda function which accepts a string as an argument and returns true
if the given string matches the original regex pattern.
Inside the Lambda function, we will use the std::regex_match(str, pattern)
function to check if the string str
matches the regex pattern or not.
The std::any_of()
function will return true if any element from the string array arr
matches the given regex pattern
.
Like, in the below example, we will check if any string in array starts with a substring “Th” or not.
Frequently Asked:
- How to initialize an Array with same value in C++?
- Pass an Array by reference to function in C++
- Check If Array Contains Duplicates in C++
- How to reverse an array in C++?
Let’s see the complete example,
#include <iostream> #include <algorithm> #include <regex> #include <string> int main() { // A string array const char * arr[] = {"Why", "Where", "Here", "This", "What"}; // A Regex Pattern std::regex pattern("Th.*"); // Check if any string in array matches the given regex pattern // i.e. check if any string starts with the substring "Th" bool result = std::any_of( std::begin(arr), std::end(arr), [&](const std::string& str) { return std::regex_match(str, pattern); }); if(result) { std::cout << "Yes, at least one string in array matches the regex pattern. \n"; } else { std::cout << "No, none of the string in array matches the regex pattern. \n"; } return 0; }
Output :
Yes, at least one string in array matches the regex pattern.
Summary
Today we learned about a way to check if any element in array matches regex pattern in C++. Thanks.