I am using gtest to do unit test and trying to use the function MatchesRegex
to match the pattern a string contains multiple substrings using look around. e.g
Verifying the statement The team members are Tom, Jerry and a Terminator
contains all three keywords Tom
, Jerry
and Term
std::string target = "The team members are Tom, Jerry and a Terminator";
EXPECT_THAT(target, MatchesRegex("(?=.*(Tom))(?=.*(Jerry))(?=.*(Term))"));
But I am getting an error
Regular expression "((?=.*(Tom))(?=.*(Jerry))(?=.*(Term)))" is not a valid POSIX Extended regular expression.
Any suggestion to fix the regexp?
The test code can be found here
POSIX regular expressions in C++ are very limited. Fortunately, you may combine expectations logically.
#include <iostream>
#include <string>
#include <gmock/gmock.h>
using testing::AllOf;
using testing::MatchesRegex;
TEST(RegexTest, Simple_Regex_Matcher) {
std::string target = "The team members are Tom, Jerry and a Terminator";
EXPECT_THAT(target, AllOf(MatchesRegex(".*Tom.*"), MatchesRegex(".*Jerry.*"), MatchesRegex(".*Term.*")));
}
int main(int argc, char*argv[]) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
Output:
[==========] Running 1 test from 1 test suite.
[----------] Global test environment set-up.
[----------] 1 test from RegexTest
[ RUN ] RegexTest.Simple_Regex_Matcher
[ OK ] RegexTest.Simple_Regex_Matcher (0 ms)
[----------] 1 test from RegexTest (0 ms total)
[----------] Global test environment tear-down
[==========] 1 test from 1 test suite ran. (0 ms total)
[ PASSED ] 1 test.