Check If Any Element in Array Matches Regex Pattern in C++
source link: https://thispointer.com/check-if-any-element-in-array-matches-regex-pattern-in-c/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Check If Any Element in Array Matches Regex Pattern in C++
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.
Advertisements
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.
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.
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK