簡體   English   中英

(C ++)確定不匹配的正則表達式捕獲組

[英](C++) Determine the unmatched regex capture groups

我想檢查密碼是否滿足以下要求:

這應該:

  • 包含至少1個小寫字母(ASCII 97-122)
  • 包含至少1個字母(65-90)
  • 至少包含1位數字
  • 包含至少1個特殊字符(33-47、58-64、91-96、123-126)
  • 長度介於8到20個字符之間

它還應該告訴我這些要求中哪些沒有滿足。


給定以下表達式,我可以使用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 
std::regex rx("^((?=.*[a-z]))?((?=.*[A-Z]))?((?=.*[0-9]))?((?=.*[!-/:-@[-`{-~]))?(\\S){8,20}$");

並檢查mr[i].first == str.end() 演示

話雖如此,回想一下俗話

有些人在遇到問題時會認為“我知道,我會使用正則表達式”。 現在他們有兩個問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM