How the pattern works
| Part | Meaning |
|---|---|
(?:[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 falsePython
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.