views:

257

answers:

4

I think its simple but I am too dumb to write one. Can someone proovide me with a regular expression that checks a given string for atleast 1 letter and atleast 1 number.

Also please give some explanation.

A: 

This would obviously be much easier with two checks, one for the string, one for the number.

Something like the following might work though, seeing as if you have both a number and a letter then you must by definition have a number next to a letter (or vice versa):

([A-Za-z][0-9]|[0-9][A-Za-z])

Update: removed a spurious '|'. Note, the above assumes no other characters are valid, which I suppose might not be acceptable. See other answer for a better solution if punctuation is allowed.

samjudson
I didn't downvote you (not my style) but it appears to me that your RE will match the strings "0", "A" and so on, even though they don't have a letter and a number. It may be that your second "|" is there by accident but even then I think your assumption is wrong - the description seems to indicate that "0,A" would be valid and it doesn't have a number next to a letter.
paxdiablo
Thanks - spurious '|' in there which wasn't my original intent. It does annoy me when people downvote without saying why, I'll just have to assume it was because of what you said :)
samjudson
Yes, that was why I downvoted.
CiscoIPPhone
+5  A: 

REs aren't that good for very complicated things like multiple orders but this simple one should be representable with:

[A-Za-z].*[0-9]|[0-9].*[A-Za-z]
paxdiablo
can this expression be modified to validate this: !1$$aawdEEQ!
Eros
er, it does... .
annakata
oops, yes it does, thanks a lot :)
Eros
A: 

A best way would be separately check for this, using 2 regex: /[a-z]/i and /\d/.

Else, assuming you want to enforce the security rule for a password, split it (e.g. in PHP with str_split) and count the number of occurence of each character type, which will give you an estimation of the password strength and let you adapt your rules.

Performance is not an issue if this for password change, you don't do it on 20K stings...

streetpc
A: 

Someone has already answered but you might find this useful also...

Its a visual regular expression builder written in .NET. Its pretty cool, you can see in real time what you will get. Check it out here.

:)

Chalkey