正则表达式 - 如何忽略匹配组的顺序? [英] Regex - how to ignore order of the matched groups?
问题描述
我正在尝试为密码创建一个正则表达式验证:
I'm trying to create a regex validation for a password which is meant to be:
- 6个字符长
- 至少有一个az
- 至少有一个AZ
- 有一个0-9
- 6+ characters long
- Has at least one a-z
- Has at least one A-Z
- Has at leat one 0-9
因此,换句话说,比赛将有:
So, in other words, the match will have :
- 至少一个az,AZ,0-9
- 至少3个任何其他字符
我想出了:
((.*){3,}[a-z]{1,}[A-Z]{1,}[0-9]{1,})
看起来很简单对我而言合乎逻辑,但有两件事情出错:
it seems pretty simple and logical to me, but 2 things go wrong:
- 量词
{3,}
for(。*)
以某种方式不起作用并破坏整个正则表达式。起初我最后有{6,}
但是正则表达式会影响内部组中的量词,因此需要[AZ] {6 ,}
而不是[AZ] {1,}
- 当我删除
{3,}
正则表达式有效,但只有当这些组有序时才会匹配 - 这样它将匹配aaBB11
,但不是BBaa11
- quantifier
{3,}
for(.*)
somehow doesn't work and destroys whole regex. At first I had{6,}
at the end but then regex would affect the quantifiers in inner groups, so it will require[A-Z]{6,}
instead of[A-Z]{1,}
- when I remove
{3,}
the regex works, but will match only if the groups are in order - so that it will matchaaBB11
, but notBBaa11
推荐答案
这是一个用途我不会使用单个正则表达式但多个更简单的表达式的情况。
This is a use case where I wouldn't use a single regular expression, but multiple simpler ones.
仍然,回答你的问题:如果你只想要要验证密码是否符合这些条件,您可以使用前瞻:
Still, to answer your question: If you only want to validate that the password matches those criteria, you could use lookaheads:
^(?=.{6})(?=.*?[a-z])(?=.*?[A-Z])(?=.*?[0-9])
你基本上是在找一个你看的位置
You're basically looking for a position from which you look at
- 6个字符(也许更多跟随,没关系):
(?=。{6})
- 也许有些人ng,然后是一个小写字母:
(?=。*?[az])
- 也许某事,然后是大写字母:
(?=。*?[AZ])
- 也许是东西,然后是数字:
(?=。 *?[0-9])
- 6 characters (and maybe more to follow, doesn't matter):
(?=.{6})
- maybe something, then a lowercase letter:
(?=.*?[a-z])
- maybe something, then an uppercase letter:
(?=.*?[A-Z])
- maybe something, then a digit:
(?=.*?[0-9])
由于,外观顺序是任意的也许是部分。
(注意我已将 6个字符长解释为至少6个字符。)
(Note that I've interpreted 6 characters long as at least 6 characters long.)
这篇关于正则表达式 - 如何忽略匹配组的顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!