我正在尝试匹配文字数字,例如1600442 在 Microsoft Visual Studio 2010 中使用一组正则表达式。我的正则表达式很简单:
1600442|7654321
7895432
问题是以上两个都匹配字符串。
在 Python 中实现它会得到预期的结果: 导入重新
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);
}
结果:
请注意,Python re.match
仅在字符串的开头搜索模式匹配,因此我建议在每个字符串的开头使用 ^
(字符串的开头)模式。
关于c++ - MSVC 正则表达式匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33495994/