1

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?

6
  • Which regex.h? The Unix one? You should better specify that, since it's not a standard C++ or C header. Commented May 4, 2011 at 0:43
  • I'm just using the one that's already there, so the default, whatever that is. I'm in OSX, which is basically the same as Linux. Commented May 4, 2011 at 0:50
  • What is your compiler and OS? Anyway, if you want cross-platform and cross-compiler compatibility and a good OO interface, I suggest trying Boost.Regex. boost.org/doc/libs/1_46_1/libs/regex/doc/html/index.html Commented May 4, 2011 at 0:51
  • I'm in OSX and I'm using g++. Commented May 4, 2011 at 0:53
  • You have two very different regular expression libraries available to you. #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. Commented May 4, 2011 at 2:30

2 Answers 2

4
#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"; } 
Sign up to request clarification or add additional context in comments.

Comments

1

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

That details the usage of <regex>. The OP asked for an example of <regex.h>. They are not the same API.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.