Google 使用 C++11/14 测试,如何修复无效的 POSIX 扩展错误
Google test using C++11/14, how to fix the invalid POSIX Extended error
我正在使用 gtest 进行单元测试,并尝试使用函数 MatchesRegex
来匹配字符串包含多个子字符串的模式,使用环视。例如
验证语句 The team members are Tom, Jerry and a Terminator
包含所有三个关键字 Tom
、Jerry
和 Term
std::string target = "The team members are Tom, Jerry and a Terminator";
EXPECT_THAT(target, MatchesRegex("(?=.*(Tom))(?=.*(Jerry))(?=.*(Term))"));
但是我收到一个错误
Regular expression "((?=.*(Tom))(?=.*(Jerry))(?=.*(Term)))" is not a valid POSIX Extended regular expression.
有任何修复正则表达式的建议吗?
可以找到测试代码here
POSIX C++ 中的正则表达式非常有限。幸运的是,您可以将期望合乎逻辑。
#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();
}
输出:
[==========] 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.
我将的答案标记为已接受的答案。但在我的最终解决方案中,我使用了类似
EXPECT_THAT(target, AllOf(HasSubstr("Tom"), HasSubstr("Jerry"), HasSubstr("Term")));
灵感来自 的回答。 Regexp 更短更慢,但 AllOf+HasSubstr 具有更好的可读性。
我正在使用 gtest 进行单元测试,并尝试使用函数 MatchesRegex
来匹配字符串包含多个子字符串的模式,使用环视。例如
验证语句 The team members are Tom, Jerry and a Terminator
包含所有三个关键字 Tom
、Jerry
和 Term
std::string target = "The team members are Tom, Jerry and a Terminator";
EXPECT_THAT(target, MatchesRegex("(?=.*(Tom))(?=.*(Jerry))(?=.*(Term))"));
但是我收到一个错误
Regular expression "((?=.*(Tom))(?=.*(Jerry))(?=.*(Term)))" is not a valid POSIX Extended regular expression.
有任何修复正则表达式的建议吗?
可以找到测试代码here
POSIX C++ 中的正则表达式非常有限。幸运的是,您可以将期望合乎逻辑。
#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();
}
输出:
[==========] 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.
我将
EXPECT_THAT(target, AllOf(HasSubstr("Tom"), HasSubstr("Jerry"), HasSubstr("Term")));
灵感来自