vc++正则表达式匹配长字符串

VC++ regular expression match long string

本文关键字:字符串 正则表达式 vc++      更新时间:2023-10-16

我有以下代码:

#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;
    }
}

它工作得很好,如果正则表达式是像"myemail@domain.com",但如果我尝试"myemail@domain.com:anothermail@domain.com:useless string:blah blah"它失败了!

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

我成功了,但是对于一些REGEX模式它失败了:

#include <regex>
#include <iostream>
#include <string>
int main () {
    std::string str("mymail@yahoo.com;lslsls;myemail@gmail.com");
    std::tr1::regex rx("[a-zA-Z0-9_\.]+@([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;
}

这里不是mymail@yahoo.commyemail@gmail.com而是yahoo.cgmail.

regex_match用于检查字符串是否符合确切的模式。

你要么使用regex_search,取决于你的需求,要么你的模式必须涵盖所有的可能性。看一下Regex