the Compartmented Robust Posix C++ Unit Test system | hosted by |
---|
Regular expression matching is used with
ASSERT_PRED(pred, ...)
and
crpcut::match
<matcher>(...) instantiated
with crpcut::regex. 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_PRED(crpcut::match<crpcut::regex>(fmt, crpcut::regex::e), el.pop()); ASSERT_PRED(crpcut::match<crpcut::regex>(fmt, crpcut::regex::e), el.pop()); } 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.
![]() | Note |
---|---|
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" -------------------------------------------------------------- /home/bjorn/devel/crpcut/doc-src/samples/regex-simple.cpp:67 ASSERT_PRED(crpcut::match<crpcut::regex>(fmt, crpcut::regex::e), el.pop()) param1 = 1 what else happened? crpcut::match<crpcut::regex>(fmt, crpcut::regex::e) : did not match ------------------------------------------------------------------------------- =============================================================================== Total 1 test cases selected UNTESTED : 0 PASSED : 0 FAILED : 1
![]() | 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. |