[英](C++) Determine the unmatched regex capture groups
I want to check if a password meets the following requirements: 我想检查密码是否满足以下要求:
It should: 这应该:
It should also tell me which of these requirements did it not meet. 它还应该告诉我这些要求中哪些没有满足。
Given the following expression I can validate it with regex_match() from std::regex
library 给定以下表达式,我可以使用
std::regex
库中的regex_match()对其进行验证
regex re("^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!-/:-@[-`{-~])(\\S){8,20}$");
But this way I can only know if it matches or does not, as it returns a boolean
但是这样我只能知道它是否匹配,因为它返回一个
boolean
Given this, I tried iterating over the match_results
like below, after adding some capture groups to the expression. 鉴于此,在将一些捕获组添加到表达式后,我尝试遍历如下所示的
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;
}
And it produced the following output: 它产生了以下输出:
size: 6
index: 0 --> AAAaaa111$$$
index: 1 --> AA
index: 2 --> Aa
index: 3 -->
index: 4 -->
index: 5 --> $
tests passed
Press any key to continue . . .
What I'd like to achieve is to tell which of the groups failed to match. 我想要实现的是告诉哪些组不匹配。 For example for input:
SamplePassword1
only the 4th group would fail to match, as it does not contain a special character. 例如,对于输入:
SamplePassword1
只有第4个组将不匹配,因为它不包含特殊字符。 The user could then be notified which specific requirement/s did the password not meet. 然后可以通知用户密码不符合哪些特定要求。 Accordingly,
SamplePassword1$
would have a match in each of the groups and pass. 因此,
SamplePassword1$
在每个组中都具有匹配项并通过。
Is this task achievable using a single regular expression rather than having a separete one for each of the requirements? 是否可以使用单个正则表达式而不是为每个需求单独使用一个正则表达式来完成此任务?
I came across a somewhat similar question here , but it's in C# .NET and uses named capturing groups. 我在这里遇到了一个类似的问题,但是它在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}$");
and check with mr[i].first == str.end()
. 并检查
mr[i].first == str.end()
。 Demo 演示
That said, recall the saying : 话虽如此,回想一下俗话 :
Some people, when confronted with a problem, think "I know, I'll use regular expressions."
有些人在遇到问题时会认为“我知道,我会使用正则表达式”。 Now they have two problems.
现在他们有两个问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.