I have to implement some code in Ruby based on Java implementation that was already done in the company. Parts of the Java code has the usage for checking if a string is base64 encoded using Base64.isArrayByteBase64(aInput) from org.apache.commons.codec.binary.Base64 library.
I did see that the Ruby's standard library includes a module Base64 to encode and decode from and to Base64. But I don't see any functionality built into Ruby that checks if a particular string is Base64 encoded or not. Is there any other library/gem out there that fulfills my requirement?
Thanks in advance.
You could do a quick check with a regular expression. Something like [A-Za-z0-9+\/]+={0,3}
is pretty close. Then check to see if the length is divisible by 4.
http://en.wikipedia.org/wiki/Base64
%r{^(?:[a-zA-Z0-9+/]{4})*(?:|(?:[a-zA-Z0-9+/]{3}=)|(?:[a-zA-Z0-9+/]{2}==)|(?:[a-zA-Z0-9+/]{1}===))$}
Is the proper regexp for rfc4648.
Ref.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With