c#中以下要求的正则表达式 [英] Regular Expression for below requirement in c#
本文介绍了c#中以下要求的正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
必须包含至少6个字母字符和至少2个数字。用户ID和密码不得包含无效字符,最大长度为12个字符。
我需要从我的数据库中获取正则表达式并验证。我不想在我的c#代码中检查它。我很抱歉让人感到困惑。
Must contain at least 6 alpha characters and at least 2 numbers. User ID and Passwords must not contain invalid characters and have a maximum length of 12 characters.
I need to get the regular expression from my database and verify. I dont want to check it in my c# code. I apologize for confusing.
推荐答案
你的数字与字母自由混合,正则表达式非常不合适。如果你想要允许所有的Unicode字母,不仅要为这样的混合编写正则表达式非常困难,任何字母的概念几乎不可能表达。使用C#,很容易做到。如果你只想要英文字符,那么使用C#也更容易。
如下:拳头,检查最大长度。然后遍历字符串并计算3个类中的字符:字母,数字和另一个。在循环之前,将两个计数器变量初始化为零:一个用于字母,一个用于数字。在一个循环中,如果出现非字母和非数字,立即返回false(失败),否则递增数字字母的计数器。
你可以使用功能
Char.IsLetter Method(Char)(系统) [ ^ ],
Char .IsDigit Method(Char)(System) [ ^ ],
或更好, Char.IsLetterOrDigit方法(字符)(系统) [ ^ ]。
如果你想允许英文cha仅限racters,只检查角色是否在A和z之间;对于其他语言,类似的检查可能不那么简单。
这就是全部。
只需一个注意:建议的标准对于密码来说真的很糟糕。您可以在许多地方阅读有关良好密码限制的建议。
-SA
It your numbers are freely mixed with letters, Regular Expression is quite unsuitable. Not only it's extremely hard to write the regular expression for such a mix, the idea of "any letter" is nearly impossible to express, if you want to allow all Unicode letters. With C#, it's easy to do. If you want, say, English characters only, it's also easier to do with C#.
Here is how: Fist, check up maximum length. Then traverse the string and count characters in 3 classes: letters, digits and the other. Before the cycle, initialize two counter variables to zero: one for letters and one for digits. In a loop, if non-letter and non-digit appears, return false (failure) immediately, otherwise increment the counter of letters of digits.
You can use the functions
Char.IsLetter Method (Char) (System)[^],
Char.IsDigit Method (Char) (System)[^],
or, even better, Char.IsLetterOrDigit Method (Char) (System)[^].
If you want to allow English characters only, just checkup that the character is between "A" and "z"; for other languages, the similar check can be not as simple.
That's all.
Just one note: the suggested criterion is really bad for a password. You can read recommendations on good password constraints in many places.
—SA
这篇关于c#中以下要求的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文