.NET正EX pression其中检查长度和非字母数字字符 [英] .NET Regular expression which check length and non-alphanumeric characters
问题描述
我需要的正则表达式验证字符串具有最小长度为6,它是包含至少一个非字母数字字符,例如:EN%{S $ U)
,h9YI>!4J
,{9YI;!4J
,恩% {S $ usdf)
,dfh9YI>!4J
,ghffg {9YI;!4J
。
这一个运作良好 ^ *(?= {6})(?=。* \\ D)。* $
但在情况下,当字符串中不包含任何数字(例如EN%{S $ U)
)这是行不通的。
^(?=。{6})(。* [^ 0-9A-ZA-Z]。* )$
我们用积极的前瞻,以确保至少有6个字符。然后我们相匹配,看起来至少有一个非字母数字字符模式( [^ 0-9A-ZA-Z]
)。该。*
的匹配任何数量的围绕这一非字母数字字符的任意字符,但我们已经检查过我们,我们在这里达成的时间匹配的至少6
^ *(?= {6})(?=。* \\ D)。* $
是您尝试正则表达式。下面是一些建议:
- 您不需要在先行匹配超过6个字符。匹配这里只有6并没有经常EX pression其余从匹配600多限制。
-
\ D
匹配一个数字,而(?=。* \\ D)
是一个超前一对他们。这就是为什么你遇到你喜欢EN%字符串提到的问题{S $ U)
。 - 即使上面的观点是不是不正确的,在这里经常EX pression是正确的,你可以结合第二个先行与
。*
下面由只使用。* \\Ð。*
。
I need Regexp to validate string has minimum length 6 and it is contains at least one non-alphanumeric character e.g: "eN%{S$u)"
, "h9YI!>4j"
, "{9YI!;4j"
, "eN%{S$usdf)"
, "dfh9YI!>4j"
, "ghffg{9YI!;4j"
.
This one is working well ^.*(?=.{6,})(?=.*\\d).*$"
but in cases when string does not contain any numbers(e.g "eN%{S$u)"
) it is not working.
^(?=.{6})(.*[^0-9a-zA-Z].*)$
We use positive lookahead to assure there are at least 6 characters. Then we match the pattern that looks for at least one non-alphanumeric character ([^0-9a-zA-Z]
). The .*
's match any number of any characters around this one non-alphanumeric character, but by the time we've reached here we've already checked that we're matching at least 6.
^.*(?=.{6,})(?=.*\\d).*$"
is the regex you tried. Here are some suggestions:
- You don't need to match more than 6 characters in the lookahead. Matching only 6 here does no restrict the rest of the regular expression from matching more than 6.
\d
matches a digit, and(?=.*\\d)
is a lookahead for one of them. This is why you are experiencing the problems you mentioned with strings likeeN%{S$u)
.- Even if the point above wasn't incorrect and the regular expression here was correct, you can combine the second lookahead with the
.*
that follows by just using.*\\d.*
.
这篇关于.NET正EX pression其中检查长度和非字母数字字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!