Regex Patterns

Base64 Encoded String

Match standard Base64 encoded strings with optional padding.

What Is This?

This regex pattern validates standard Base64 encoded strings. Base64 encoding uses A-Z, a-z, 0-9, +, / characters and = for padding. The pattern ensures the string length is a multiple of 4 and padding (if present) is valid. For URL-safe Base64, use - instead of + and _ instead of /.

How to Use

1

The Pattern

Use this pattern to validate Base64 input before attempting to decode. This prevents decoding errors from malformed Base64 strings. The pattern handles all padding variants: no padding (length multiple of 4), single padding (ends with =), and double padding (ends with ==).

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

Examples

Example

Valid Base64 strings

Matches:
SGVsbG8gV29ybGQ=
U29tZURhdGE=
MTIzNDU2Nzg5MA==
dGVzdA==

Does not match:
Invalid!
base64!!!
SGVsbG8gV29ybGQ
Example

Various lengths

Matches:
YQ==
YWI=
YWJj
YWJjZA==

Does not match:
abc
12345
!!!!

Related Entries

More from this reference:

Frequently Asked Questions

Should I validate Base64 before decoding?

Yes. Validating before decoding prevents runtime errors from malformed input. However, validation does not guarantee the decoded result is meaningful — just that it is structurally valid Base64.

Does this pattern work for URL-safe Base64?

No. URL-safe Base64 uses - and _ instead of + and /. For URL-safe Base64, use: ^(?:[A-Za-z0-9-_]{4})*(?:[A-Za-z0-9-_]{2}==|[A-Za-z0-9-_]{3}=)?$. This is used in JWT tokens.