JSON Web Token (JWT) — Structure Validation Regex for Java
/^([A-Za-z0-9_-]+)\.([A-Za-z0-9_-]+)\.([A-Za-z0-9_-]+)$/What this pattern does
This page provides a well-structured, multi-part regular expression for matching json web token (jwt) — structure validation, ported and verified for Java. In security-sensitive code, using an unverified regex can open the door to both false positives and denial-of-service attacks. The snippet below is ready to drop into your Java project — whether you're validating in a Spring Boot controller, a Jakarta EE service, or a standalone utility class.
Java Implementation
// JSON Web Token (JWT) — Structure Validation
// ReDoS-safe | RegexVault — Security > API Keys & Tokens
import java.util.regex.Pattern;
public class JsonWebTokenJwtStructureValidationValidator {
private static final Pattern PATTERN =
Pattern.compile("^([A-Za-z0-9_-]+)\\.([A-Za-z0-9_-]+)\\.([A-Za-z0-9_-]+)$");
public static boolean validate(String input) {
return PATTERN.matcher(input).matches();
}
// Example
public static void main(String[] args) {
System.out.println(validate("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c")); // true
}
}Test Cases
Matches (Valid) | Rejects (Invalid) |
|---|---|
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c | eyJhbGci.eyJzdWI.sig.extra |
header.payload.signature | eyJhbGci.eyJzdWI |
aaa.bbb.ccc | not.a.jwt.at.all.here |
| — | a.b. |
When to use this pattern
This pattern is drawn from the Security > API Keys & Tokens category and carries a ReDoS-safe certification. That matters for Java developers because critical in Java applications since the JVM regex engine uses backtracking and is susceptible to ReDoS without careful pattern design. RegexVault audits patterns against known backtracking attack vectors, ensuring you have the necessary context before using this regex in a high-stakes production environment.
Common Pitfalls
Never trust a JWT whose signature you have not verified. The 'alg: none' attack bypasses signature verification. Never accept tokens with algorithm 'none'. Validate expiry (exp claim) — expired tokens must be rejected.
Technical Notes
Structure only — does not validate header algorithm, payload claims, expiry, or signature. Three segments: header (base64url) + payload (base64url) + signature (base64url, may be empty for 'none' algorithm — always reject 'none'). Capture groups: 1=header, 2=payload, 3=signature.
Have a pattern that belongs in the vault?
Submit it for review — community-verified patterns get credited to your GitHub handle. Free submissions join the queue. Priority review available for $15.
Submit a Pattern