dazzafact
dazzafact

Reputation: 2860

Regex: match letters WITH numbers only

How can I create a regex expression that will match only letters with numbers?

I've tried something like (?>[A-z]+)([a-z0-9]+).

The regex should give the following result:

1234b --> true
1234 --> false
abcd --> false
abcd4 --> true
12b34 --> true

Upvotes: 13

Views: 17105

Answers (4)

Andy Lester
Andy Lester

Reputation: 93636

Don't make it be one regex if you don't have to. Use two regexes that both have to match. In Perl, it would be like this

if ( /[a-zA-Z]/ && /\d/ ) 

Upvotes: 0

sleepsort
sleepsort

Reputation: 1331

^([a-Z]+[0-9]+|[0-9]+[a-Z]+)[a-Z0-9]*$

and a simpler version inspired by TimPietzcker:

^([a-Z]+[0-9]|[0-9]+[a-Z])[a-Z0-9]*$

Upvotes: 1

marcus erronius
marcus erronius

Reputation: 3693

(?:\d+[a-z]|[a-z]+\d)[a-z\d]*

Basically, where 1 and a are any number and any letter, it matches 1a or a1, surrounded by any number of alphanumeric characters.

edit: shorter and probably faster now

Upvotes: 14

Maccath
Maccath

Reputation: 3956

Other answers are incorrect, and will allow any string that only contains letters, numbers or both. My expression will specifically exclude strings that consist only of letters or only of numbers.

[A-Za-z0-9]*([a-zA-Z]+[0-9]+|[0-9]+[a-zA-Z]+)

Any number of letters and numbers, followed by at least one letter followed by a number or at least one number followed by a letter.

There is possibly a simpler way of doing this, however. Mine seems long winded. Maybe it's not. Anyone care to pitch in? :P

Upvotes: 6

Related Questions