Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex only allow alphanumeric

Tags:

regex

I am trying to do the following with regex...

  • Only A-Z and 0-9
  • Not one character in its own
  • Can not be just numbers on their own
  • Can be just letters on their own but at least 2 characters

I have this so far http://regex101.com/r/yW1pV8 ...

.*[a-zA-Z]{2,}+.*

This seems to meet my critera except that it doesn't stop me from putting in other charactes such as $ _ ! etc...

Some correct test data is...

579 International Road
International Road

Some incorrect data is...

679
3
$£
A

Where am I going wrong?

like image 389
fightstarr20 Avatar asked Apr 02 '14 00:04

fightstarr20


People also ask

How do I allow only special characters in regex?

You can use this regex /^[ A-Za-z0-9_@./#&+-]*$/.

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

Which is a sample regular expression that accepts alphanumeric characters only?

The regex \w is equivalent to [A-Za-z0-9_] , matches alphanumeric characters and underscore.


1 Answers

.* matches anything, which isn't what you want it seems. Also, you don't need the +, since X{n,} already means X at least n times. Lastly, you forgot the 0-9 part. So it looks like this will do:

[a-zA-Z0-9]{2,}

Some regex flavors have [a-zA-Z0-9] as a pre-defined character class. For example, in Java it's \p{Alnum}.

If you also want to allow for spaces (as per your test data), use \s:

(?:\s*[a-zA-Z0-9]{2,}\s*)*
like image 64
arshajii Avatar answered Oct 26 '22 08:10

arshajii