Coder
Coder

Reputation: 3130

Regex to have a number or a special character

I have a following regex but it doesnt seem to work as expected.

I want one lowercase letter, one uppercase letter, one digit or one special character.

The length should be minimum 8 char.

(^.*(?=.{8,})(?=.*\\d)(?=.*[a-z])(?=.*[A-Z]).*$)

Can anyone help please

Upvotes: 2

Views: 3292

Answers (2)

alpha bravo
alpha bravo

Reputation: 7948

a little more efficient pattern = ^(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%^&*_0-9])(.{8,})$ Demo

Upvotes: 1

Floris
Floris

Reputation: 46445

I see two problems. You have a double backslash in front of your digit specifier - make it a single. Also you don't have an expression for "special characters". I have added an expression to include some special characters - you can adapt that to your need (be careful - some have special meaning, for example -).

Demonstration at http://regex101.com/r/kM5xW6

Expression (updated to reflect "one digit OR one special character"):

(^.*(?=.{8,})(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%^&*_0-9]).*$)

This requires at least 8 characters, a lower case letter, an upper case letter, and a character from the list !@#$%^&*_0-9 (which is "one of the special characters or a digit between 0 and 9).

Upvotes: 2

Related Questions