2013-01-02 28 views
1

我有followig代码:VC++正则表达式匹配长的字符串

#include <regex> 
#include <iostream> 
#include <string> 

int main() 
{ 
    std::tr1::regex rx("(\\w+)(\\.|_)?(\\w*)@(\\w+)(\\.(\\w+))+"); 
    std::string s; 
    std::getline(std::cin,s); 
    if(regex_match(s.begin(),s.end(),rx)) 
    { 
     std::cout << "Matched!" << std::endl; 
    } 
} 

它运作良好,如果正则表达式是一样的东西"[email protected]"但如果我尝试"[email protected]:[email protected]:useless string:blah blah" 它失败!

我能做些什么来匹配有效的字符串(最终打印出找到的字符串,只有匹配的部分不是全部字符串)?

我成功莫名其妙,但也有一些正则表达式模式失败:

#include <regex> 
#include <iostream> 
#include <string> 

int main() { 
    std::string str("[email protected];lslsls;[email protected]"); 
    std::tr1::regex rx("[a-zA-Z0-9_\\.][email protected]([a-zA-Z0-9\\-]+\\.)+[a-zA-Z]{2,4}"); 
    std::tr1::sregex_iterator first(str.begin(), str.end(), rx); 
    std::tr1::sregex_iterator last; 

    for (auto it = first; it != last; ++it) 
    { 
     std::cout << "[Email] => " << it->str(1) << std::endl; 
    } 

    return 0; 
} 

这里不是获取[email protected][email protected]我得到yahoo.cgmail.

+0

忘了给我的REGEX添加'“()”',解决了! – bsteo

回答

3

regex_match用于检查一个字符串的精确模式。

您可以使用regex_search,这取决于您的要求或您的图案必须涵盖所有可能性。 看看Regex

+0

你是对的!正则表达式搜索可以做到这一点,并且可以工作!你有什么想法,我该怎么做,并打印出匹配的字符串?就像从“[email protected]:[email protected]:无用的字符串:等等等等”中打印出“[email protected]”并剥离不匹配的文本? – bsteo

+0

按照链接,有一些代码片段。 – masche

相关问题