Using ?=. in regular expression

前端 未结 2 1939
执笔经年
执笔经年 2021-01-31 18:59

I saw the phrase

^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])[A-Za-z0-9_#@%\\*\\-]{8,24}$

in regex, which was password checking mechanism. I read few cou

相关标签:
2条回答
  • 2021-01-31 19:32

    (?=regex_here) is a positive lookahead. It is a zero-width assertion, meaning that it matches a location that is followed by the regex contained within (?= and ). To quote from the linked page:

    lookaround actually matches characters, but then gives up the match, returning only the result: match or no match. That is why they are called "assertions". They do not consume characters in the string, but only assert whether a match is possible or not. Lookaround allows you to create regular expressions that are impossible to create without them, or that would get very longwinded without them.

    The . is not part of the lookahead, because it matches any single character that is not a line terminator.

    0 讨论(0)
  • 2021-01-31 19:32

    Although i am a newbie to regex but what i understand about the above regex is

    1- ?= is positive lookahead i.e. it matches the expression by looking ahead and sees if there is any pattern that matches your search paramater like [A-Z]

    2- .* makes sure that they can be 0 or more number of characters before your matching expression i.e. it makes sure that u can lookahead till the end of the input string to find a match. In short * is a quantifier which says 0 or more so if:

    For instance u changed * with ? for [A-Z] part then your expression will only return true if ur 1st or 2nd letter is capital. OR if u changed it with + then ur expression will return true if any letter other than the first is a capital letter

    0 讨论(0)
提交回复
热议问题