vc++正则表达式匹配长字符串
VC++ regular expression match long string
我有以下代码:
#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.com
和myemail@gmail.com
而是yahoo.c
和gmail.
regex_match
用于检查字符串是否符合确切的模式。
你要么使用regex_search
,取决于你的需求,要么你的模式必须涵盖所有的可能性。看一下Regex
相关文章:
- 使用正则表达式regex_search在字符串中查找字符串
- 如何在C++中使用正则表达式"|"后选择字符串?
- 如何在 c++11 中使用正则表达式找到确切的子字符串?
- 如何编写将验证以下字符串的正则表达式?
- C++带有捕获组的正则表达式字符串文本
- 如何使用正则表达式从字符串中提取值
- 使用正则表达式c++从单词和分隔符之间的字符串中提取所有子字符串
- 如何在没有外部库的情况下使用C++03约束执行基于正则表达式的字符串操作
- 需要忽略日期/序列号,但匹配字符串其余部分的正则表达式
- 如何将正则表达式向量与一个字符串匹配?
- 正则表达式匹配字符串之间的数字
- 如何根据某个索引将字符串与正则表达式匹配?
- 如何从字符串变量为正则表达式构建原始字符串
- C++ 中用于搜索字符串模式的正则表达式
- C++无符号字符串类型的正则表达式
- 如何使用正则表达式将输入数字格式化为字符串
- 使用具有特殊字符的正则表达式标记 C++ 字符串
- C 11正则表达式和字符串U8前缀
- 正则表达式:从模式字符串 1.string2'string3 中提取字符串,其中字符串 1 可以包含 '." 字符
- 在字符串正则表达式c++中查找模式