检查字符串是否为base64 [英] check if string is 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.name
和string.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屋!