[英](C++) Determine the unmatched regex capture groups
我想檢查密碼是否滿足以下要求:
這應該:
它還應該告訴我這些要求中哪些沒有滿足。
給定以下表達式,我可以使用std::regex
庫中的regex_match()對其進行驗證
regex re("^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!-/:-@[-`{-~])(\\S){8,20}$");
但是這樣我只能知道它是否匹配,因為它返回一個boolean
鑒於此,在將一些捕獲組添加到表達式后,我嘗試遍歷如下所示的match_results
。
std::string str("AAAaaa111$$$");
std::regex rx("^((?=.*[a-z]).*)((?=.*[A-Z]).*)((?=.*[0-9]).*)((?=.*[!-/:-@[-`{-~]).*)(\\S){8,20}$");
std::match_results< std::string::const_iterator > mr;
std::regex_search(str, mr, rx);
std::cout << "size: " << mr.size() << '\n'; // 6 or 0 only ?
for (int i = 0; i < mr.size(); i++) {
std::cout << "index: " << i << "\t --> \t" << mr.str(i) << endl;
}
if (regex_match(str, rx)) {
cout << "tests passed" << endl;
}
else {
cout << "tests failed" << endl;
}
它產生了以下輸出:
size: 6
index: 0 --> AAAaaa111$$$
index: 1 --> AA
index: 2 --> Aa
index: 3 -->
index: 4 -->
index: 5 --> $
tests passed
Press any key to continue . . .
我想要實現的是告訴哪些組不匹配。 例如,對於輸入: SamplePassword1
只有第4個組將不匹配,因為它不包含特殊字符。 然后可以通知用戶密碼不符合哪些特定要求。 因此, SamplePassword1$
在每個組中都具有匹配項並通過。
是否可以使用單個正則表達式而不是為每個需求單獨使用一個正則表達式來完成此任務?
我在這里遇到了一個類似的問題,但是它在C#.NET中,並使用了命名捕獲組。
var re = new Regex("((?<a>a)|(?<b>b))"); var ma = re.Match("a"); Console.WriteLine("a in a: " + ma.Groups["a"].Success); //true Console.WriteLine("b in a: " + ma.Groups["b"].Success); //false
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.