Can someone explain how this regex works? The case was:"You must enter at least at 6 characters, and no space, including special characters!"
matches(^(?=.*\\W)(?=.*[a-zA-Z])(?!.*\\s).{6,}$);
CodePudding user response:
(?=...)
is a positive lookahead assertion, and it tests whether the expression ...
matches anything immediately ahead of the current position
(?!...)
is a negative lookahead assertion, and it tests whether the expression ...
does NOT match the text immediately ahead of the current position
\W
means "non-word", eg any character that's not a digit, letter or underscore.[a-zA-Z]
means any letter a through z or A through Z (eg. letters of the english/latin alphabet)\s
means "whitespace"
So :
(?=.*\\W)
ensure at least 1 non-word character occurs(?=.*[a-zA-Z])
ensures at least 1 letter occurs(?!.*\\s)
ensure no whitespace occurs.{6,}
will only match if the string is at least 6 characters long (because there won't be any 6-character-or-longer substring to match against at the start of the string if the total length of the string is any shorter)