[英]C++ std::regex Regular Expressions Finding multiple matches
我試圖用c ++解析證書,並認為這是學習正則表達式的好機會。 我剛剛在大約一個小時前了解了正則表達式,所以請原諒我缺乏知識。
我正在尋找與條目相關的所有OU。
我正在做以下事情:
std::smatch OuMatches;
std::string myCertSubject = "O=\"My Company, Incorporated\", OU=Technician Level - A3, OU=Access Level - 1, CN=\"Name, My\", E=namem@company.com";
std::regex subjectRx("OU=[[:w:]|[:s:]|[:digit:]|-]*", std::regex_constants::icase);
bool foundOU = std::regex_search(mySubject,OuMatches,subjectRx);
為什么這不能給我所有與我的reg ex匹配的結果(2)? 有沒有辦法得到這個?
看起來你只是想獲得一個看起來像OU=XXXXXXXXXXXXXXXXX
后跟逗號或分號的字符串。
這個正則表達式會這樣做:
OU=[^,;]+
這意味着字符串OU=
,后跟至少一個不是逗號或分號的字符:
[^,;]+
這是使用此正則表達式打印匹配項的代碼示例(基於此處的示例):
std::smatch OuMatches;
std::string myCertSubject = "O=\"My Company, Incorporated\", OU=Technician Level - A3, OU=Access Level - 1, CN=\"Name, My\", E=namem@company.com";
std::regex subjectRx("OU=[^,;]+", std::regex_constants::icase);
std::regex_iterator<std::string::iterator> it (myCertSubject.begin(), myCertSubject.end(), subjectRx);
std::regex_iterator<std::string::iterator> end;
while (it != end)
{
std::cout << it->str() << std::endl;
++it;
}
請嘗試使用否定的字符類。 我覺得你的角色課不像你認為的那樣......
subjectRx("OU=[^,]*", std::regex_constants::icase);
[^,]*
將匹配除逗號之外的所有字符。
至於匹配,請嘗試使用循環:
while (std::regex_search (mySubject,OuMatches,subjectRx)) {
// do something
}
我不太了解C ++,但我發現這個文檔頁面我認為應該更有用。
它在這里的代碼是
while (std::regex_search (s,m,e)) {
for (auto x:m) std::cout << x << " ";
std::cout << std::endl;
s = m.suffix().str();
}
編輯:我只是意識到你可以在參數中使用逗號,例如在O=
,這將不會與[^,]
。 相反,你可以使用這個正則表達式:
OU=(?:[^,]|,(?!(?:[^"]*"[^"]*"[^"]*)*$))*
你可以看到一個O=
這里的例子。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.