2011-05-04 168 views
0

我正在使用正则表达式使用#include <regex.h>如果我有一个字符串s,如何使用正则表达式来搜索模式p?如何使用正则表达式从C++字符串中提取字符串

+0

哪个regex.h? Unix的?您应该更好地指定它,因为它不是标准的C++或C标头。 – 2011-05-04 00:43:23

+0

我只是使用已经存在的那个,所以默认情况下,无论如何。我在OSX中,它基本上与Linux相同。 – neuromancer 2011-05-04 00:50:26

+0

你的编译器和操作系统是什么?无论如何,如果你想跨平台和交叉编译器兼容性和一个很好的面向对象接口,我建议尝试Boost.Regex。 http://www.boost.org/doc/libs/1_46_1/libs/regex/doc/html/index.html – 2011-05-04 00:51:27

回答

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"; 
} 
+0

这是在Visual Studio中工作吗? – jjxtra 2013-01-25 20:42:02

1

检查http://msdn.microsoft.com/en-us/library/bb982821.aspx,具有详细的正则表达式使用模式。来自MS vc博客。

 const regex r("[1-9]\\d*x[1-9]\\d*"); 

     for (string s; getline(cin, s);) { 
       cout << (regex_match(s, r) ? "Yes" : "No") << endl; 
     } 
+3

详细说明了''的用法。 OP要求提供一个''的例子。他们不是同一个API。 – 2011-05-04 02:27:24

相关问题