首页 > 解决方案 > How to understand a particular regular expression pattern?

问题描述

I found this regex online but I am struggling to understand it. It is this:

(?=^.{6,10}$)(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%^&*()_+}{":;'?/>.<,])(?!.*\s).*$

http://regexlib.com/Search.aspx?k=password&c=-1&m=5&ps=100

The description is:

This regular expression match can be used for validating strong password. It expects at least 1 small-case letter, 1 Capital letter, 1 digit, 1 special character and the length should be between 6-10 characters. The sequence of the characters is not important. This expression follows the above 4 norms specified by Microsoft for a strong password.

I see there are the following groups. I have read that ?= means look ahead.

标签: regex

解决方案


你对第一组是正确的。因为它在开头和结尾都用^and锚定$,所以它必须匹配整个输入。所以它要求有6-10个字符。

接下来的四个前瞻需要.*在开始时匹配输入中任何位置所需的字符类型。如果您只是编写(?=\d+)它,则必须匹配输入中当前位置的数字,即开头。通过为它们中的每一个加上前缀.*,它允许不同的类型(数字、小写、大写、标点符号)以任何顺序排列。你不需要+在它后面加上,因为匹配一次就足够了。

(?!.*\s)前瞻。\s匹配空格,因此这意味着字符串不能包含任何空格。

最后,.*$只匹配整个输入。这只是在所有的前瞻之后有一些东西所需要的。


推荐阅读