10

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?

1
  • Your example has no test data....... Commented Apr 2, 2014 at 0:33

2 Answers 2

10

.* 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*)*
Sign up to request clarification or add additional context in comments.

6 Comments

That doesnt work for me with my test data, I have updated the original post with this data
@fightstarr20 Looks like you also want to allow for spaces. See the edit.
Yeah just spotted that, was missing the space! This now works better but does still allow numbers to be on their own
Plus, now the space counts as a character
@fightstarr20 Ok, I'm starting to understand the requirements. Try the edit.
|
0
var pattern = new RegExp(/^(?=.*\d)(?=.*[a-zA-Z]).{2,}$/);
alert(pattern.test(value) + value);

For alpha number

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.