Regex for Base64 — Pattern Explained with Examples
DodaTech
Updated Jun 20, 2026
2 min read
Base64 encoding is used to transmit binary data over text-based protocols like email (MIME), HTTP headers, and data URIs. This regex validates whether a string is a properly formatted Base64 encoded value with correct padding.
The Pattern
/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/Pattern Breakdown
| Part | Meaning |
|---|---|
^ | Start-of-string anchor |
(?:[A-Za-z0-9+/]{4})* | Zero or more groups of exactly 4 valid Base64 characters |
(?:[A-Za-z0-9+/]{2}== | Optionally match 2 chars followed by == padding |
|[A-Za-z0-9+/]{3}= | Or match 3 chars followed by = padding |
)? | Make the padding group optional |
$ | End-of-string anchor |
Matches
dGhpcyBpcyBhIHRlc3Q=SGVsbG8gV29ybGQhaGVsbG8=YWJjZGVmZw==U29mdHdhcmUgRW5naW5lZXJpbmc=
Does NOT Match
dGhpcyBpcyBhIHRlc3Q(no padding, wrong length)text!!!SGVsbG8gV29ybGQ(wrong length)base64!!==aGVsbG8=AA(too long)
Language Examples
JavaScript
const base64Regex = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
console.log(base64Regex.test('SGVsbG8gV29ybGQh')); // true
console.log(base64Regex.test('text!!!')); // false
Python
import re
pattern = r'^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$'
print(bool(re.match(pattern, 'SGVsbG8gV29ybGQh'))) # True
print(bool(re.match(pattern, 'text!!!'))) # FalseCommon Pitfalls
- Padding length depends on input length: one char of padding (
=) for 3 remaining bytes, two (==) for 2, none for multiples of 3 - URL-safe Base64 replaces
+with-and/with_, which this pattern does not handle - Whitespace and MIME line breaks are allowed in many real-world Base64 strings but will cause this pattern to reject them
- Base64 length must be divisible by 4 after padding — missing or extra padding characters break decoding
- This pattern validates structure only, not content — a valid Base64 string may decode to garbage
Real-World Use Cases
- Data URIs in HTML/CSS — validate Base64-encoded images embedded directly in web pages
- JWT token parsing — JWT headers and payloads are Base64url-encoded; validate structure before decoding
- Email attachment processing — MIME attachments use Base64; validate before attempting to decode binary content
FAQ
Related Patterns
Regex for UUID Regex for Hex Color
Previous
Regex for File Extension — Pattern Explained with Examples
Next
Regex for Domain Name — Pattern Explained with Examples
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro