Regular expressions in string comparisons

3,929 views
Skip to first unread message

GTester

unread,
Dec 25, 2010, 2:02:16 AM12/25/10
to Google C++ Testing Framework
Hi,
Is it possible to do use regular expressions somehow in googletest,
such as something like:
EXPECT_EQ("SomePrefix.*", teststring);

Sorry if I've missed something obvious in the documentation, but I
can't find any detailed information on this. The last sentence in the
'String Comparison' section (http://code.google.com/p/googletest/wiki/
Primer#Basic_Assertions) talks about string comparison tricks such as
regular expressions as if they're quite possible and refers you to the
"Advanced Google Test Guide". That guide doesn't seem to discuss
'string comparison tricks' anywhere, although it talks about regular
expressions being used only in the context of Death Tests (which isn't
what I'm after).

Thanks in advance,
Rob.

GTester

unread,
Dec 25, 2010, 6:07:43 PM12/25/10
to Google C++ Testing Framework
I have since discovered the RE class in gtest, so I can do something
like:
using namespace ::testing::internal;
EXPECT_TRUE(RE::FullMatch(teststring, RE("SomePrefix.*")));

Along similar lines another respondent suggested using Boost's RegEx
(regex_search()) which may be more future-proof given that the RE
class might not be always be accessible as it is in an 'internal'
namespace.

Rob

Dirk Meister

unread,
Dec 26, 2010, 7:23:04 AM12/26/10
to GTester, Google C++ Testing Framework
You could also use the RE class from the RE2 open source project:
http://code.google.com/p/re2/

Probably the RE class in gtest is internal to avoid "collisions" with
the RE2 project.

Dirk

Zhanyong Wan (λx.x x)

unread,
Dec 28, 2010, 1:08:22 PM12/28/10
to GTester, Google C++ Testing Framework

As you found out, you cannot count on testing::internal::RE working in
the future.

If you could upgrade to Google Mock, which is a super set of Google
Test, you can use its various matchers, including regular expression
matchers:

http://code.google.com/p/googlemock/wiki/CheatSheet#String_Matchers

Your example will look like

using testing::MatchesRegex;
EXPECT_THAT(teststring, MatchesRegex("SomePrefix.*"));

or

using testing::StartsWith;
EXPECT_THAT(teststring, StartsWith("SomePrefix"));

You don't have to use Google Mock for its mocking ability -- it
contains many goodies for regular testing as well.

--
Zhanyong

Reply all
Reply to author
Forward
0 new messages