[英]MSVC regular expression match
我正在嘗試使用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);
}
結果:
請注意,Python re.match
僅在字符串的開頭搜索模式匹配,因此我建議在每個模式的開頭使用^
(字符串的開始)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.