Dev
Dev

Reputation: 6710

RegEx to check the string contains least one alphabet or digit

I want a regular expression that check string must contain least an alphabet [a-zA-Z] or a digit. All other special characters are allowed, but only special characters or only spaces or only spaces with special characters will now be accepted.

I have tried /\b(?=[A-Z]*[0-9])(?=[0-9]*[A-Z])[\s\S]\b/i and ^(a-zA-Z0-9).*[\s\S]*$ and ^(a-zA-Z0-9).*[\s].*[\S]*$ etc. But its not working. Awaiting for your valuable response.

Thanks

Upvotes: 3

Views: 13656

Answers (4)

Bhairesh M
Bhairesh M

Reputation: 145

(?=.*?[0-9])(?=.*?[A-Za-z]).+
Allows special characters and makes sure at least one number and one letter.

(?=.*?[0-9])(?=.*?[A-Za-z])(?=.*[^0-9A-Za-z]).+
Demands at least one letter, one digit and one special-character. 

The first one does not demand special chars, only allows them.

Upvotes: 0

ΩmegaMan
ΩmegaMan

Reputation: 31596

^(?=.*[\w\d]).+

This pattern will fail if there is not at least one character or one digit with any combination of special characters and spaces.

Upvotes: 5

Firas Dib
Firas Dib

Reputation: 2621

I'm not sure I understood you correctly, but from what I've gathered you want to have atleast one letter (a-z, 0-9) in the string. This regex will do just that: /^(?=.*[a-z\d]).+/igm

(Set the flags however they need to be set in asp.net. The m-flag might be redundant for you, I only used it for the demo. The g-flag likely does not exist. If so, just remove it.)

Demo+explanation: http://regex101.com/r/jY9fJ5

Upvotes: 2

Andrew Cheong
Andrew Cheong

Reputation: 30273

If you want at least one alphabet or digit, followed by only spaces and symbols:

/^.*[a-zA-Z0-9][^a-zA-Z0-9]*$/

If you want only one alphabet or digit, followed by the same:

/^[^a-zA-Z0-9]*[a-zA-Z0-9][^a-zA-Z0-9]*$/

I can't imagine what else it is that you are looking for. Examples would help immensely.

Upvotes: 1

Related Questions