开发者

How to check if a string is base 64 encoded in Ruby?

开发者 https://www.devze.com 2023-01-13 23:32 出处:网络
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.is

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 librar开发者_Python百科y/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.

0

精彩评论

暂无评论...
验证码 换一张
取 消