Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex: match only letters WITH numbers

Tags:

regex

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
like image 457
dazzafact Avatar asked Dec 19 '12 11:12

dazzafact


2 Answers

(?:\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

like image 193
marcus erronius Avatar answered Nov 15 '22 15:11

marcus erronius


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

like image 27
Maccath Avatar answered Nov 15 '22 15:11

Maccath