regexhelper
Test a pattern. Copy a ready-made one. No signup.

Regex to Match a Base64 String

Copy the pattern, paste your text below, and check whether a value is valid Base64. Below the tester: how the padding rule works and why length must be a multiple of four.

/ /

What this pattern matches

This expression validates a standard Base64 string — the encoding used for data URIs, JWT payloads, and email attachments. It enforces the alphabet A–Z a–z 0–9 + / and the correct trailing = padding.

How it works, part by part

(?:[A-Za-z0-9+/]{4})* — zero or more full four-character groups.

[A-Za-z0-9+/]{2}== — a final group of two characters plus two padding signs, or…

[A-Za-z0-9+/]{3}= — a final group of three characters plus one padding sign.

The ^ and $ anchors force the whole string to be valid Base64.

Why length must be a multiple of four

Base64 packs three bytes into four characters, so a complete string is always a multiple of four characters, padded with = when the input is not divisible by three. For URL-safe Base64 replace +/ with -_ and drop the padding requirement.

Use it in your code

Python
import re
text = "SGVsbG8gd29ybGQh"
pattern = r'''^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$'''
for m in re.finditer(pattern, text):
    print(m.group())
JavaScript
const text = "SGVsbG8gd29ybGQh";
const re = new RegExp(String.raw`^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$`, "g");
console.log(text.match(re));

FAQ

Does it accept URL-safe Base64?

Not as written. URL-safe Base64 uses - and _ instead of + and /, and often omits padding. Swap the characters and make the padding group optional.

Why is there no g flag?

It is a whole-string validator anchored with ^ and $, so you test one candidate at a time rather than finding many.

Will it catch a wrongly padded string?

Yes. Strings whose length is not a multiple of four, or with padding in the wrong place, fail the anchors.