Regex for base64 string

Use /^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$/ to check that a whole string is a valid for base64 string. Every example below is tested against the pattern, and you can open it in the Regex Tester with the samples preloaded.

Updated

/^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$/
Open in Regex Tester
InputResult
SGVsbG8=✓ Match
SGVsbG8gd29ybGQ=✓ Match
QUJD✓ Match
SGVsbG8✗ No match
SGV$bG8=✗ No match
=abc✗ No match
SGVsbG8==✗ No match

How the pattern works

PartMeaning
(?:[A-Za-z0-9+\/]{4})*Complete four-character blocks
[A-Za-z0-9+\/]{2}==Or a final block with two padding signs
[A-Za-z0-9+\/]{3}=Or a final block with one padding sign

Code examples

JavaScript

const re = /^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$/;
re.test(value); // true or false

Python

import re

bool(re.fullmatch(r'(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?', value))

PHP

preg_match('/^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$/', $value) === 1;

Notes and limitations

The empty string also matches, so check the length separately. For base64url (JWTs, URLs) replace +\/ with _- and make the padding optional. Decode with the Base64 Encoder/Decoder.

Regex TesterType a pattern and watch matches highlight live in your test text.
Open the tool

Frequently asked questions

What is the regex for base64 string?
/^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$/ — it matches the whole string. See the table above for what each part does.
Which examples match?
Of the examples tested, these match: SGVsbG8=, SGVsbG8gd29ybGQ=, QUJD. The others don’t.
How do I test this regex?
Click “Open in Regex Tester” — the pattern, flags and sample text load automatically, and matches highlight as you edit.