我有以下代码:
#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.com
和 myemail@gmail.com
我获取 yahoo.c
和 gmail。
最佳答案
regex_match
用于检查字符串是否符合精确模式。
要么使用 regex_search
,具体取决于您的要求,或者您的模式必须涵盖所有可能性。
看看Regex
关于c++ - VC++正则表达式匹配长字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14119295/