I'm using regex by using #include <regex.h> If I have a string s, how can I use regex to search for a pattern p?
2 Answers
#include <regex.h> #include <iostream> #include <string> std::string match(const char *string, char *pattern) { // Adapted from: http://pubs.opengroup.org/onlinepubs/009695399/functions/regcomp.html int status; regex_t re; regmatch_t rm; if (regcomp(&re, pattern, REG_EXTENDED) != 0) { return "Bad pattern"; } status = regexec(&re, string, 1, &rm, 0); regfree(&re); if (status != 0) { return "No Match"; } return std::string(string+rm.rm_so, string+rm.rm_eo); } int main(int ac, char **av) { // e.g. usage: ./program abcdefg 'c.*f' std::cout << match(av[1], av[2]) << "\n"; } Comments
Check http://msdn.microsoft.com/en-us/library/bb982821.aspx, has detailed usage patter for regex. from MS vc blog.
const regex r("[1-9]\\d*x[1-9]\\d*"); for (string s; getline(cin, s); ) { cout << (regex_match(s, r) ? "Yes" : "No") << endl; } 1 Comment
Robᵩ
That details the usage of
<regex>. The OP asked for an example of <regex.h>. They are not the same API.
#include <regex.h>is the C library, standardized by POSIX.1-2001.#include <regex>is the C++ library standardized in C++ TR1. You will probably find the C++ regular expression library more useful.