Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex to check the string contains only letter and numbers but not only numbers

Tags:

regex

php

I need a help with regex which checks the string contains only letter and numbers but not only numbers

Valid

* letters
* 1wret
* 0123chars
* chars0123
* cha2rs

Invalid

* 1324
* xcvxxc%$#
* xcv123xxc%$#
* _012chars
* _test
like image 897
ondrobaco Avatar asked Jul 29 '10 10:07

ondrobaco


People also ask

How do you check if a string only has letters and numbers?

To check whether a String contains only unicode letters or digits in Java, we use the isLetterOrDigit() method and charAt() method with decision-making statements. The isLetterOrDigit(char ch) method determines whether the specific character (Unicode ch) is either a letter or a digit.

How do I allow only letters and numbers in regex?

You can use regular expressions to achieve this task. In order to verify that the string only contains letters, numbers, underscores and dashes, we can use the following regex: "^[A-Za-z0-9_-]*$".

How do you check if a string contains only numbers regex?

To check if a string contains only numbers in JavaScript, call the test() method on this regular expression: ^\d+$ . The test() method will return true if the string contains only numbers. Otherwise, it will return false . The RegExp test() method searches for a match between a regular expression and a string.

Which method returns true if a string consists of only letters and numbers and is not blank?

The isalnum() method returns True if all characters in the string are alphanumeric (either alphabets or numbers). If not, it returns False.


3 Answers

Here are the components of the regex we're going to use:

  • ^ and $ are the beginning and end of the string anchors respectively
  • \d matches a digit
  • [a-zA-Z] matches a letter
  • [a-zA-Z\d] matches a letter or a digit
  • * is "zero-or-more" repetition

With these, we can now compose the regex we need (see on rubular.com):

^\d*[a-zA-Z][a-zA-Z\d]*$

Here's an explanation of the pattern:

from the beginning...  till the end
|                      |
^\d*[a-zA-Z][a-zA-Z\d]*$
 \_/\______/\_________/

The 3 parts are:

  • Maybe some digits as a prefix...
  • But then definitely a letter!
  • And then maybe some digits and letters as a suffix

References

  • regular-expressions.info/Character Class, Anchors, and Repetition
like image 118
polygenelubricants Avatar answered Nov 15 '22 09:11

polygenelubricants


This should do it:

^[0-9]*[a-zA-Z]+[a-zA-Z0-9]*$

This requires at least one character of [a-zA-Z].

like image 44
Gumbo Avatar answered Nov 15 '22 08:11

Gumbo


[a-z0-9]*[a-z]+[a-z0-9]*
like image 31
Vitalii Fedorenko Avatar answered Nov 15 '22 08:11

Vitalii Fedorenko