gpt4 book ai didi

c# - 使用 RegEx 验证字符串是否为 base64 格式?

转载 作者:可可西里 更新时间:2023-11-01 03:06:41 26 4
gpt4 key购买 nike

我一直在寻找如何验证 base64 字符串并遇到了这个问题。

 ^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$

我需要一些帮助来让它允许“==”和“=”。

谢谢

最佳答案

这应该表现得非常好。

private static readonly HashSet<char> _base64Characters = new HashSet<char>() { 
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/',
'='
};

public static bool IsBase64String(string value)
{
if (string.IsNullOrEmpty(value))
{
return false;
}
else if (value.Any(c => !_base64Characters.Contains(c)))
{
return false;
}

try
{
Convert.FromBase64String(value);
return true;
}
catch (FormatException)
{
return false;
}
}

关于c# - 使用 RegEx 验证字符串是否为 base64 格式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3355407/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com