# Regex for Base64 Strings

> Base64 regex that checks the alphabet, length and = padding of standard Base64, with a Base64URL variant for JWTs and URLs. Explained token by token.

```
/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/
```

Standard Base64 uses A–Z, a–z, 0–9, + and /, in blocks of four characters, with one or two = signs padding the final block. This pattern enforces all three rules, so a string with the wrong length or misplaced padding fails. It also accepts the empty string, which is valid Base64 for zero bytes.

## Token by token

| Token | Meaning |
|---|---|
| `^(?:[A-Za-z0-9+/]{4})*` | any number of complete four-character blocks |
| `(?:` | then, optionally, a final padded block: |
| `[A-Za-z0-9+/]{2}==` | two characters and two = signs (one leftover byte) |
| `\|[A-Za-z0-9+/]{3}=` | or three characters and one = sign (two leftover bytes) |
| `)?$` | end of string |

## Examples

- ✓ matches: `SGVsbG8=`
- ✓ matches: `SGVsbG8gd29ybGQ=`
- ✓ matches: `QUJD`
- ✓ matches: `YQ==`
- ✗ does not match: `SGVsbG8`
- ✗ does not match: `SGVsbG8===`
- ✗ does not match: `SGV$bG8=`
- ✗ does not match: `a=b=`

## Variations

- `^[A-Za-z0-9_-]+$` — Base64URL without padding, as used in JWTs (- and _ replace + and /)
- `^(?=.)(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$` — the same as the main pattern, but rejects the empty string

## Language notes

- MIME-encoded Base64 wraps lines at 76 characters. Remove whitespace before validating — in JavaScript, value.replace(/\s+/g, "").

## FAQ

### Does a match mean the string is Base64-encoded data?

Not necessarily. Plenty of ordinary words — 'test', 'abcd' — are valid Base64 by shape. A match tells you a decoder will accept the string, not that someone encoded it.

### Why does a JWT segment fail this pattern?

JWTs use Base64URL: - and _ instead of + and /, and no padding. Use the Base64URL variation.

## Related patterns

- [Regex for JSON Web Tokens (JWT)](https://www.devkult.com/regex/jwt.md)
- [Regex for UUID Validation](https://www.devkult.com/regex/uuid.md)
- [Regex for Hex Color Codes](https://www.devkult.com/regex/hex-color.md)

Open the interactive page: https://www.devkult.com/regex/base64