Miguel Moura
Miguel Moura

Reputation: 39364

Best option available to allow empty string with a Regex

I have a Regex to validate a password: at least one uppercase, one lowercase, one number and one special character:

^(?=[^a-z]*[a-z])(?=[^A-Z]*[A-Z])(?=\D*\d)(?=.*[$@$!%*?&,;.:-_])[A-Za-z\d$@$!%*?&,;.:-_]+

But I also want to allow empty because I will validate it in another way.

So I tried to options:

^((?=[^a-z]*[a-z])(?=[^A-Z]*[A-Z])(?=\D*\d)(?=.*[$@$!%*?&,;.:-_])[A-Za-z\d$@$!%*?&,;.:-_]+)*$

NOTE: I wrapped the Regex in () and added *$ at the end;

Or the following:

^$|(?=[^a-z]*[a-z])(?=[^A-Z]*[A-Z])(?=\D*\d)(?=.*[$@$!%*?&,;.:-_])[A-Za-z\d$@$!%*?&,;.:-_]+

NOTE: Added $| at start ...

What is the best approach? One of these 2 or some other?

Upvotes: 1

Views: 134

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626738

If you have a regex matching at least something, but not the whole string, you need to use an alternation with $:

^(?:(?=[^a-z]*[a-z])(?=[^A-Z]*[A-Z])(?=\D*\d)(?=.*[$@$!%*?&,;.:_-])[A-Za-z\d$@$!%*?&,;.:_-]+|$)
^^^^                                                                                        ^^^

See the regex demo. Look:

  • ^ - start of string
  • (?: - An alternation group start
    • (?=[^a-z]*[a-z])(?=[^A-Z]*[A-Z])(?=\D*\d)(?=.*[$@$!%*?&,;.:_-])[A-Za-z\d$@$!%*?&,;.:_-]+ - match this
    • | - or...
    • $ - end of string.
  • ) - end of the alternation

If you had a pattern that matched the whole string (say, ^\d+\s+\w+$ to match strings like 12 Apr), and you would like to also match an empty string, you could just enclose with an optional pattern:

^(?:\d+\s+\w+)?$
 ^^^         ^^

Details:

  • ^ - start of string
  • (?:\d+\s+\w+)? - one or zero sequences of 1+ digtis followed with 1+ whitespaces followed with 1+ alphanumerics/underscores
  • $ - end of string

Upvotes: 1

Related Questions