检查字符串是否为base64 [英] check if string is base64

查看:81
本文介绍了检查字符串是否为base64的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可能会收到以下两个字符串:

i may recieve these two strings:

    base = Base64.encode64(File.open("/home/usr/Desktop/test", "rb").read)
    => "YQo=\n"

    string = File.open("/home/usr/Desktop/test", "rb").read
    => "a\n"

到目前为止,我一直尝试用正则表达式i-e检查字符串. /([A-Za-z0-9+\/]{4})*([A-Za-z0-9+\/]{4}|[A-Za-z0-9+\/]{3}=|[A-Za-z0-9+\/]{2}==$)/,但是如果文件很大,这将非常繁琐.

what i have tried so far is to check string with regular expression i-e. /([A-Za-z0-9+\/]{4})*([A-Za-z0-9+\/]{4}|[A-Za-z0-9+\/]{3}=|[A-Za-z0-9+\/]{2}==$)/ but this would be very heavy if the file is big.

我也尝试过base.encoding.namestring.encoding.name,但是都返回相同的结果.

I also have tried base.encoding.name and string.encoding.name but both returns the same.

我还看到了这篇文章并得到了正则表达式解决方案,但还有其他解决方案吗?

I have also seen this post and got regular expression solution but any other solution ?

有什么主意吗?我只想得到的是字符串实际上是文本还是base64编码的文本....

Any idea ? I just want to get is the string is actually text or base64 encoded text....

推荐答案

您可以使用类似这样的方法,虽然性能不高,但是可以保证不会得到误报:

You can use something like this, not very performant but you are guaranteed not to get false positives:

require 'base64'

def base64?(value)
  value.is_a?(String) && Base64.encode64(Base64.decode64(value)) == value
end

这篇关于检查字符串是否为base64的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆