PatternRegex

Validate a Base64 string

Check that a string is well-formed standard Base64 — groups of four characters from the A-Z/a-z/0-9/+/ alphabet, with correct = padding at the end.

Last updated

Pattern
^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$
Open in Regex Tester & Builder

Matches

  • SGVsbG8sIFdvcmxkIQ==
  • YQ==

Doesn’t match

  • not base64 at all!!
  • SGVsbG8_IFdvcmxk

Why it’s written this way

(?:[A-Za-z0-9+/]{4})* consumes as many complete four-character groups as the string has — Base64 always encodes in units of four output characters per three input bytes. The final optional group then handles the two padding shapes a string can legally end with: two data characters plus '==', or three data characters plus a single '='.

Anchoring with ^ and $ matters here more than in most patterns in this library — without them, a string with garbage at the start or end would still report a match on the valid portion inside it, which defeats the point of validating the whole string.

Edge cases to know

  • An empty string technically satisfies this pattern, since the repeated group can match zero times and the padding group is optional — decide separately whether empty input should count as valid for your use case.
  • This is the standard alphabet only. Base64url, used in JWTs and URLs, swaps + and / for - and _ and usually drops padding, so it needs a different pattern.
  • Matching the shape does not mean the content decodes to anything meaningful — it only proves the string is legal Base64 syntax.

Related in Patterns