Course contentsShow
← Java
Lesson 2289 of 2,87044. Regular ExpressionsFree lesson

Username and Identifier Patterns

Define patterns for valid usernames with length constraints, allowed characters, and naming conventions.

Username and Identifier Patterns

What you'll learn: How to define regular expression patterns that enforce username and identifier constraints like length, allowed characters, and naming conventions.

Why Usernames Need Pattern Validation

When users create accounts or you validate identifiers in your application, you need to enforce rules: minimum/maximum length, allowed characters (letters, numbers, underscores), and naming conventions (no spaces, must start with a letter, etc.). Regular expressions provide a clean way to codify these requirements into a single pattern.

Common Username Pattern Rules

Think of username validation like a bouncer checking IDs at a club—specific criteria must be met before entry is granted. Typical rules include:

  • Length constraints: 3-16 characters
  • Starting character: Must begin with a letter
  • Allowed characters: Letters, digits, underscores, hyphens
  • Case sensitivity: Usually case-insensitive
  • No spaces or special symbols

Building the Pattern

Here's a pattern for a username that must be 3-16 characters, start with a letter, and contain only letters, digits, and underscores:

String usernamePattern = "^[a-zA-Z][a-zA-Z0-9_]{2,15}$";

Breaking it down:

  • ^ - Start anchor
  • [a-zA-Z] - First character must be a letter
  • [a-zA-Z0-9_]{2,15} - Next 2-15 characters: letters, digits, or underscore
  • $ - End anchor

For identifiers allowing hyphens and requiring 4-20 total characters:

String identifierPattern = "^[a-zA-Z][a-zA-Z0-9_-]{3,19}$";

Key Takeaway: Username patterns use character classes with quantifiers to enforce length, starting character rules, and allowed character sets—critical for input validation and security in user-facing applications.