Rexact
Cheatsheet

Regex Base64 string

The reference Stack Overflow question's author eventually posted their own regex in an update to the question - but a comment (7 votes) points out it contains a real typo: the start-of-string "^" only binds to the first branch of an alternation, leaving the other two unanchored. Our analysis goes further: this pattern is vulnerable to ReDoS (polynomial complexity), verified concretely - a roughly 95,000-character string, almost entirely "=" signs, locks up the JavaScript engine for over 2 seconds. The "simplified" fix suggested in that same comment has its own real flaw: a stray hyphen in the character class (a Base64 URL-safe character, not standard Base64) and no check that the number of "=" matches the number of preceding characters. Here's a safe pattern compliant with RFC 4648, compared against both of those attempts and the "just check that every character is valid" approach the question itself describes as working 99% of the time.

/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/
passes 20/20 cases

Comparison of existing patterns

Implementation

const re = new RegExp("^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$", "");
re.test(input);

Limits

  • Valide uniquement la FORME (alphabet et structure de remplissage) : une chaîne peut être syntaxiquement un Base64 valide sans pour autant décoder vers des données cohérentes ou exploitables.
  • Ne couvre que l'alphabet Base64 standard (« + » et « / ») : la variante URL-safe (RFC 4648 §5, qui remplace ces deux caractères par « - » et « _ » et omet généralement le remplissage) nécessite un motif différent.
  • Accepte la chaîne vide comme un Base64 valide (zéro octet de données) : selon le contexte d'utilisation, ce cas limite peut nécessiter un rejet explicite en dehors de la regex elle-même.
  • N'impose aucune limite de longueur : une chaîne de plusieurs millions de caractères, si sa structure est correcte, reste acceptée — à combiner avec un contrôle de taille séparé si la donnée décodée doit rester bornée.