Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a RegEx to validate a Base32 :: RFC 3548

Tags:

regex

php

rfc

I want to validate a Base32 code before converting it. Is there a way to do this such as regular expression? I need to follow these standards by RFC 3548

like image 899
Jacob Finamore Avatar asked Dec 08 '14 16:12

Jacob Finamore


1 Answers

This should do it:

^(?:[A-Z2-7]{8})*(?:[A-Z2-7]{2}={6}|[A-Z2-7]{4}={4}|[A-Z2-7]{5}={3}|[A-Z2-7]{7}=)?$

Demo

The (?:[A-Z2-7]{8})* part handles 40-bit sequences. The second part handles the final bytes as specified by the spec. Note that this pattern will accept an empty string too (0 bytes).

In PHP, use this with preg_match:

$isMatch = preg_match('#^(?:[A-Z2-7]{8})*(?:[A-Z2-7]{2}={6}|[A-Z2-7]{4}={4}|[A-Z2-7]{5}={3}|[A-Z2-7]{7}=)?$#', $input);
like image 119
Lucas Trzesniewski Avatar answered Sep 25 '22 01:09

Lucas Trzesniewski