c++ - VC++正则表达式匹配长字符串

标签 c++ regex

我有以下代码:

#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废话” 它失败!

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

我以某种方式成功了,但是对于某些 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

关于c++ - VC++正则表达式匹配长字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14119295/

相关文章:

javascript - JS 帮助有选择地将 html 转义到预览区域

java - java.util.regex 是否缓存已编译的模式?

regex - 在 flex(词法分析器)中是否可以进行反向引用?

Python正则表达式获取日期形式的日志文件

c++ - 限制整数范围

c++ - 简单的 3x3 矩阵逆代码 (C++)

c++ - 动态创建指针数组时,Visual Studio 不显示完整数组

c++ - 隐式定义的析构函数有什么作用

关于 Stack Unwinding 问题的 Java 和 C++

javascript - 使用 Grunt-Replace 替换 HTML 标签