我正在尝试使用Microsoft Visual Studio 2010中的一组正则表达式来匹配文字数,例如1600442。我的正则表达式很简单:
1600442|7654321
7895432
问题是上述两个都与字符串匹配。
在Python中实施此操作可获得预期的结果:import re
serial = "1600442"
re1 = "1600442|7654321"
re2 = "7895432"
m = re.match(re1, serial)
if m:
print "found for re1"
print m.groups()
m = re.match(re2, serial)
if m:
print "found for re2"
print m.groups()
提供输出
found for re1
()
这是我所期望的。但是,在C ++中使用此代码:
#include <string>
#include <iostream>
#include <regex>
int main(){
std::string serial = "1600442";
std::tr1::regex re1("1600442|7654321");
std::tr1::regex re2("7895432");
std::tr1::smatch match;
std::cout << "re1:" << std::endl;
std::tr1::regex_search(serial, match, re1);
for (auto i = 0;i <match.length(); ++i)
std::cout << match[i].str().c_str() << " ";
std::cout << std::endl << "re2:" << std::endl;
std::tr1::regex_search(serial, match, re2);
for (auto i = 0;i <match.length(); ++i)
std::cout << match[i].str().c_str() << " ";
std::cout << std::endl;
std::string s;
std::getline (std::cin,s);
}
给我:
re1:
1600442
re2:
1600442
这不是我所期望的。我为什么在这里比赛?
该smatch
不被覆盖的第二次调用regex_search
因此,保持不变,并且包含了第一名的成绩。
您可以将正则表达式搜索代码移动到单独的方法:
void FindMeText(std::regex re, std::string serial)
{
std::smatch match;
std::regex_search(serial, match, re);
for (auto i = 0;i <match.length(); ++i)
std::cout << match[i].str().c_str() << " ";
std::cout << std::endl;
}
int main(){
std::string serial = "1600442";
std::regex re1("^(?:1600442|7654321)");
std::regex re2("^7895432");
std::cout << "re1:" << std::endl;
FindMeText(re1, serial);
std::cout << "re2:" << std::endl;
FindMeText(re2, serial);
std::cout << std::endl;
std::string s;
std::getline (std::cin,s);
}
结果:
请注意,Pythonre.match
仅在字符串的开头搜索模式匹配项,因此我建议^
在每个模式的开头使用(字符串的开头)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句