the Compartmented Robust Posix C++ Unit Test system |
|
---|
Regular expressions are preferably matched using the
pseudo operator =~(),
but can also be matched using
crpcut::match
<matcher>(...) instantiated
with crpcut::regex, with
ASSERT_PRED(pred, ...)
or
VERIFY_PRED(pred, ...)
. This is
easiest to show with an example:
#include <crpcut.hpp> #include <string> #include <list> #include <sstream> class event_list { public: event_list() : num(0) {} void push(std::string text) { event_text.push_back(text); } std::string pop() { std::ostringstream os; os << num++ << " " << event_text.front(); event_text.pop_front(); return os.str(); } private: std::list<std::string> event_text; size_t num; }; const char fmt[] = "^(\\+)?[[:digit:]]+" "[[:space:]]+" "[[:alnum:]]([[:alnum:]|[:space:]])*$"; // i.e. LINE_FMT is a positive integer followed by at least one space and // then a string of at least one alphanumerical character and spaces. TEST(verify_output_format) { event_list el; el.push("something happened"); el.push("what else happened?"); ASSERT_TRUE(el.pop() =~ crpcut::regex(fmt, crpcut::regex::e)); ASSERT_TRUE(el.pop() =~ crpcut::regex(fmt, crpcut::regex::e)); } int main(int argc, char *argv[]) { return crpcut::run(argc, argv); }
The flag crpcut::regex::e
matches the string against an extended regular expression. Other
flags are crpcut::regex::i
for
ignoring case, and crpcut::regex::m
for multi line patterns.
Caution | |
---|---|
Be careful with patterns containing “\”, since C/C++ interprets them as character escapes. |
The output from the short test program is:
FAILED!: verify_output_format phase="running" -------------------------------------------------------------- samples/regex-simple.cpp:65 ASSERT_TRUE(el.pop() =~ crpcut::regex(fmt, crpcut::regex::e)) is evaluated as: 1 what else happened? =~ regex("^(\+)?[[:digit:]]+[[:space:]]+[[:alnum:]]([[:alnum:]|[:space:]])*$") ------------------------------------------------------------------------------- =============================================================================== 1 test cases selected Sum Critical Non-critical FAILED : 1 1 0
Note | |
---|---|
With crpcut::regex you can only
assert that strings match a regular expression. If you need more
advanced functionality, for example picking sub strings for decisions,
you have to use either regcomp() and
regexec() , or C++std::regex if your compiler supports it. |
Tip | |
---|---|
The site http://www.regular-expressions.info contains a wealth of info on regular expressions, if you feel rusty. |