问题描述
我要提供的数据标注的正则表达式为所指定的密码:
I have to provide a data annotation regex for a password that's specified as:
min 8 chars
min 1 upper
min 1 lower
min 1 numeric
min 1 special char which can ONLY be one of the following:$|~=[]'_-+@. (and the password can contain no other special chars besides these)
这是特殊字符,这是给我头痛的排斥。
It's the exclusion of special characters which is giving me the headache.
我已经想出了这一点,但它只是不工作:
I've come up with this but it just does not work:
"^.*(?=.{8,})(?=.*[a-z])(?=.*[A-Z])(?=.*[\d])**(?(?!.*[^$|~=[\]'_\-+@.])|([^\W\w])).*$**
它解决了一切,我输入为无效。
It resolves everything I enter as invalid.
而这(对于特殊字符)自己做的工作:
Whereas this (for the special chars) on its own does work:
"(?(?!.*[^$|~=[\]'_\-+@.])|([^\W\w])).*$"
和我知道的第一部分工作,所以我缺少什么让他们一起工作?
and I know the first part works, so what am I missing to make them work together?
另外,有实现这一目标的一个更简单的方法?
Alternatively, is there a much simpler way of achieving this?
(.NET环境)
推荐答案
如果你真的想这样做,在一个正则表达式:
If you really want to do that in one regex pattern:
^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$|~=[\]'_+@.-])[a-zA-Z0-9$|~=[\]'_+@.-]{8,}$
这是应该做的伎俩。我们要求,下壳体,大写字母,数字和符号与向前看符号。请注意,在字符类中,你需要移动 -
到年底或逃避它。否则,它创建你不想一个字符范围。然后我们使用正常的匹配,以确保有只允许的字符,和至少8人
That should do the trick. We require, the lower case, upper case letter, digit and symbol with lookaheads. Note that in the character class, you need to move -
to the end or escape it. Otherwise it creates a character range you don't want. Then we use normal matching to ensure that there are only the allowed characters, and at least 8 of them.
不过,它通常是一个更好的方法做多个测试。单独运行这些模式:
However, it's usually a much better approach to do multiple tests. Run these patterns individually:
[a-z] // does the input contain a lower case letter?
[A-Z] // does the input contain an upper case letter?
\d // does the input contain a digit?
[$|~=[\]'_+@.-] // does the input contain one of the required symbols?
[^a-zA-Z0-9$|~=[\]'_+@.-] // are there invalid characters?
,其中前4应该返回真
,最后一个应该返回假
。此外,您可以检查 input.Length> = 8
。这使得更可读code,将让你发出相应的错误消息有关的这的条件没有被满足。
where the first 4 should return true
and the last one should return false
. In addition you can check input.Length >= 8
. This makes for much more readable code and will allow you to issue an appropriate error message about which condition is not fulfilled.
事实上,自上次的模式可以确保只有所需的字符,我们可以简化,必须有一个符号条件,以 [^ A-ZA-Z0-9]
(在这两种方法)。但我不知道这是否使事情或多或少的可读性。
In fact, since the last pattern ensures that there are only the desired characters, we can simplify the "there has to be one symbol condition" to [^a-zA-Z0-9]
(in both approaches). But I'm not sure whether that makes things more or less readable.
这篇关于普通EX pression密码与某些特殊字符排除其他所有的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!