# Regex for Username Validation

> Username regex allowing 3–16 letters, digits, and underscores, with variations for starting-letter rules and hyphens. Token breakdown included.

```
/^[a-zA-Z0-9_]{3,16}$/
```

The standard username rule: 3 to 16 characters from letters, digits, and underscore — no spaces, no symbols that need escaping in URLs or breaking in mentions. The character class plus a bounded quantifier is the whole pattern, which makes it a good first regex to actually understand rather than paste.

## Token by token

| Token | Meaning |
|---|---|
| `^` | start of string |
| `[a-zA-Z0-9_]` | one allowed character: letter, digit, or underscore (equivalent to \w in ASCII mode) |
| `{3,16}` | between 3 and 16 of them — both bounds inclusive |
| `$` | end of string — nothing else allowed |

## Examples

- ✓ matches: `dev_kult`
- ✓ matches: `User123`
- ✓ matches: `abc`
- ✗ does not match: `ab`
- ✗ does not match: `user name`
- ✗ does not match: `this_username_is_way_too_long`

## Variations

- `^[a-zA-Z][a-zA-Z0-9_]{2,15}$` — must start with a letter — avoids all-digit names that collide with IDs
- `^[a-z0-9](?:[a-z0-9-]{0,37}[a-z0-9])?$` — GitHub-style: lowercase and hyphens, no leading/trailing/only hyphen

## Language notes

- \w{3,16} looks equivalent but in Python 3 \w matches unicode letters by default — use the explicit class (or re.ASCII) if you mean ASCII only.

## FAQ

### Why 3 to 16 characters?

Convention more than law: under 3 collides and confuses, over 16 breaks layouts and mentions. Adjust the bounds to your product — the pattern shape stays the same.

### How do I forbid leading digits or trailing underscores?

Pin the first character with its own class: ^[a-zA-Z][a-zA-Z0-9_]{2,15}$ requires a letter first. For no trailing underscore, end with [a-zA-Z0-9]$ and shorten the middle quantifier by one.

## Related patterns

- [Regex for Password Validation](https://www.devkult.com/regex/password.md)
- [Regex for URL Slug Validation](https://www.devkult.com/regex/slug.md)
- [Regex for Email Validation](https://www.devkult.com/regex/email.md)

Open the interactive page: https://www.devkult.com/regex/username