Ivar Reukers
Ivar Reukers

Reputation: 7719

Java Regex - Alphabet + numbers with minimum total of 3

What have I been doing so far?

I have been searching on internet for a full hour now, but I just can't seem to find it, most answers are based on just alphabetic characters or only digits. I'm a beginner with regex and I'm trying to learn it but I just don't get it why this wouldn't work.

The problem

What I want is that (for a search machine) the input is validated with a pattern. This pattern must consist out of a minimum combination of 3 letters and or numbers. Special characters are allowed as well but there must be at least a total of 3 letters or numbers in the input.

What have I tried?

I tried using (([aA-zZ]{0,}[0-9]{0,}){3,})\w+ But this doesn't allow special characters nor does it get that I want 3 subsequential characters, because 2 are also allowed

So what would be correct and what would be incorrect?

asdA - correct - more than three in a row

as - incorrect - less than three in a row

a1s - correct - three in a row

+a1s/ correct - three in a row

+a1-s -incorrect - less than 3 in a row

Upvotes: 1

Views: 158

Answers (3)

anubhava
anubhava

Reputation: 785008

If you need to validate 3 consecutive letter or numbers then use this regex:

[A-Za-z0-9]{3}

In java use:

str.matches(".*[A-Za-z0-9]{3}.*");

Upvotes: 1

Dandelion
Dandelion

Reputation: 756

I think this would work for you:

\w*([a-zA-Z0-9]){3,}\w*

Upvotes: 0

SMA
SMA

Reputation: 37023

Try using something like:

 System.out.println("asdA".matches(".*?[a-zA-Z0-9]{3}.*?"));
 System.out.println("as".matches(".*?[a-zA-Z0-9]{3}.*?"));
 System.out.println("a1s".matches(".*?[a-zA-Z0-9]{3}.*?"));
 System.out.println("+a1s/".matches(".*?[a-zA-Z0-9]{3}.*?"));
 System.out.println("+a1-s".matches(".*?[a-zA-Z0-9]{3}.*?"));

Upvotes: 0

Related Questions