Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex: only alphanumeric but not if this is pure numeric

For instance:

'1'     => NG
'243'   => NG
'1av'   => OK
'pRo'   => OK
'123k%' => NG

I tried with

 /^(?=^[^0-9]*$)(?=[a-zA-Z0-9]+)$/

but it is not working very well.

like image 778
oldergod Avatar asked Aug 02 '12 07:08

oldergod


People also ask

How do I check if a string is alphanumeric regex?

Considering you want to check for ASCII Alphanumeric characters, Try this: "^[a-zA-Z0-9]*$" . Use this RegEx in String. matches(Regex) , it will return true if the string is alphanumeric, else it will return false.

Can alphanumeric have only numbers?

In computing, the standard alphanumeric codes, such as ASCII, may contain not only ordinary letters and numerals but also punctuation marks and math symbols.

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_-]*$".


1 Answers

So we know that there must be at least one "alphabetic" character in there somewhere:

[a-zA-Z]

And it can have any number of alphanumeric characters (including zero) either before it or after it, so we pad it with [a-zA-Z0-9]* on both sides:

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

That should do the trick.

like image 138
Andrzej Doyle Avatar answered Oct 05 '22 20:10

Andrzej Doyle