user1834664
user1834664

Reputation: 451

Regular expression for user id

I am new to regular expressions.

I have a requirement to write a regular expression with the following criteria

I have written the following expression but it does not work

^[a-zA-Z\\d*]{8,20}$

Upvotes: 5

Views: 16888

Answers (3)

SUBIN K SOMAN
SUBIN K SOMAN

Reputation: 406

Try with this code and check:

public static void main(String[] args) {
    Pattern pattern = Pattern.compile("^(?!\\d+$)\\w{8,20}$");
    Matcher matcher = pattern.matcher("Tryurcode4u");
    System.out.println("Input String matches regex - "+matcher.matches());
}

Upvotes: 0

anubhava
anubhava

Reputation: 785058

You can use this regex:

^(?!\\d+$)\\w{8,20}$

Working Demo

Upvotes: 1

zx81
zx81

Reputation: 41838

You can use this:

(?i)^(?=.*[a-z])[a-z0-9]{8,20}$

See demo of what works and what fails

  • (?i) makes it case-insensitive
  • ^ asserts that we are at the beginning of the string
  • the lookahead (?=.*[a-z]) checks that we have at least one letter
  • [a-z0-9]{8,20} matches 8 to 20 letters or digits (letters can be uppercase too)
  • $ asserts that we have reached the end of the string

Upvotes: 7

Related Questions