gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 02:57:56 25 4
gpt4 key购买 nike

我有以下代码:

#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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com