Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

only letterNumber but not all numbers

I know how to do a regex to validate if it's just letter number without no white spaces:

/^[0-9a-zA-Z]+$/

but how do I add to this regex also such that it cannot contain just numbers, so for example this is not valid:

08128912382

Any ideas?

like image 413
adit Avatar asked Dec 06 '22 03:12

adit


1 Answers

"Must contain only letters and numbers and at least one letter" is equivalent to "must contain a letter surrounded by numbers or letters":

/^[0-9a-zA-Z]*[a-zA-Z][0-9a-zA-Z]*$/

I would like to add that this answer shows a way you can think about the problem so writing the regexp is simpler. It is not meant to be the best solution to the problem. I just took what you had and gave it a nudge in the right direction.

With several more nudges, you end up with other different answers (posted by ZER0, Tomalak and OGHaza respectively) :

  1. You could notice that if there is a letter in the first or last group, the middle part is satisfied. In other words, since you have the middle part, you don't need to allow letters in the first or last part (but not both!):

    • /^[0-9]*[a-zA-Z][0-9a-zA-Z]*$/ - some numbers, followed by a letter, followed by some more numbers and letters
    • /^[0-9a-zA-Z]*[a-zA-Z][0-9]*$/ - equivalent if you read from the end
  2. Knowing about lookaheads you can assert that there is at least one letter in the string:

    • /^(?=.*[a-z])/ - matches the start of any string that contains at least 1 letter
  3. Or the other way around, as you expressed it, assert that there aren't only numbers in the string:

    • /^(?!\d+$)/ - matches the start of any string which doesn't contain just digits

The 2nd and 3rd solutions should also be combined with your original regexp that validates that the string contains only the characters you want it to (letters and numbers)

I for one am particularly fond of the 2nd solution which is i believe the fastest of all attempted so far.

like image 153
Tibos Avatar answered Dec 23 '22 02:12

Tibos