Benoît
Benoît

Reputation: 15010

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.

Upvotes: 17

Views: 18931

Answers (7)

Abhishek Gehlot
Abhishek Gehlot

Reputation: 1

this is strictly alphanumeric

String name="^[^a-zA-Z]\\d*[a-zA-Z][a-zA-Z\\d]*$";

Upvotes: 0

user2184688
user2184688

Reputation: 1

Try this: ^[a-zA-Z0-9]*[a-zA-Z]+[a-zA-Z0-9]*$

Upvotes: 0

godspeedlee
godspeedlee

Reputation: 672

try with this: ^(?!\d+\b)[a-zA-Z\d]+$
(?!\d+\b) will avoid pure numeric, add \w+ then mix alphabet and number.

Upvotes: 1

MaxArt
MaxArt

Reputation: 22637

Try with this:

/^(?!^\d*$)[a-zA-Z\d]*$/

Edit: since this is essentially the same of the accepted answer, I'll give you something different:

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

No lookaheads, no repeated complex group, it just verifies that there's at least one alphabetic character. This should be quite fast.

Upvotes: 4

davidrac
davidrac

Reputation: 10738

This should do the trick, without lookbehind:

^(\d*[a-zA-Z]\d*)+$

Upvotes: 0

Andrzej Doyle
Andrzej Doyle

Reputation: 103837

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.

Upvotes: 13

Jens
Jens

Reputation: 25593

Use

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

This expression has a negative lookahead to verify that the string is not only numbers. See it in action with RegExr.

Upvotes: 30

Related Questions