Reputation: 55489
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?
Upvotes: 1
Views: 6024
Reputation: 168626
#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";
}
Upvotes: 4
Reputation: 183
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;
}
Upvotes: 1