Kuttan Sujith
Kuttan Sujith

Reputation: 7979

Regex for upper and lower+numbers or other non-alphabetic

See my post here

Regex for at least 8 + upper and lower+numbers or other non-alphabetic

Suppose i just need this 2 condition below, what should be the regular expression?

  1. Contains upper and lower case letters.
  2. Contains numbers or other non-alphabetic characters.

I tried ^(?=.*?[a-z])(?=.*?[A-Z])(?=.*?[^a-zA-Z])$ but not working

BUT just- -(?=.*?[a-z])(?=.*?[A-Z])(?=.*?[^a-zA-Z]) is working

can i use just (?=.*?[a-z])(?=.*?[A-Z])(?=.*?[^a-zA-Z]) for the purpose?

Upvotes: 1

Views: 408

Answers (2)

Jan Turoň
Jan Turoň

Reputation: 32912

^(?=.*?[a-z])(?=.*?[A-Z])(?=.*?[^a-zA-Z])$

this means: start of string followed by anything containing lowercase or uppercase or non-alphabetic, but the next position must be end of string - this can not happen.

Your accepted aswer in your previous question is OK, is there any problem? Here you can read something more about assertions in regex http://cz.php.net/manual/en/regexp.reference.assertions.php

Upvotes: 1

stema
stema

Reputation: 93026

The problem here is that the look ahead/behind are zero-width, "non-consuming". That means your

^(?=.*?[a-z])(?=.*?[A-Z])(?=.*?[^a-zA-Z])$

will never match because the lookarounds consumed nothing and whats then left? only ^$ that would match an empty string, but this does not meet your lookahead criterias.

So you should use

^(?=.*?[a-z])(?=.*?[A-Z])(?=.*?[^a-zA-Z]).*$

that .* will consume everything and the look aheads ensure the criterias.

you can also define a length replacing the * with {x,} where x is the minimum amount of characters of the string

Upvotes: 4

Related Questions