使用正则表达式验证字符串是否为Base64格式?

16

我一直在寻找如何验证Base64字符串,然后看到了这个。

 ^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$
我需要一点帮助,使它允许"=="以及"="。谢谢。

什么意思?===已经被允许了。 - kennytm
是的,你说得对,它可以工作。抱歉,那是我在我的编码字符串上添加了一个额外的“=”来进行测试,当我需要创建一个包含“==”的新编码字符串时 :) - arbme
请注意,加号需要转义。像这样: ^(?:[A-Za-z0-9\+/]{4})*(?:[A-Za-z0-9\+/]{2}==|[A-Za-z0-9\+/]{3}=)?$ - M D P
2个回答

22

这应该表现得非常出色。

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;
    }
}

我更喜欢这个版本的清晰度,除非您预计会有很多无效数据。 - Justin
不妨使用Base64进行检查,而不是使用正则表达式...这很有道理 ;) - arbme
3
这不是一个有效的解决方案,它没有计算填充字符的数量或者字符总数。 - Sten Petrov
我的测试中第一个if..else语句总是失败的;然而你的try/catch总是有效的,但我认为长期来看这是昂贵的。 - gimlichael

8
我稍微修改了上面的代码以满足更多要求:
  • 检查正确的字符串大小(应为4的倍数)
  • 检查填充字符计数(仅应在字符串末尾有最多2个字符)
  • 使其在.NET 2.0中工作(好吧,HashSet<T> 应该被实现或使用 Dictionary<T, U>
该代码是我的断言库的一部分,因此有两个检查方法和param参数...
    private const char Base64Padding = '=';

    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 void CheckBase64String(string param, string paramName)
    {
        if (CheckBase64StringSafe(param) == false)
        {
            throw (new ArgumentException(String.Format("Parameter '{0}' is not a valid Base64 string.", paramName)));
        }
    }

    public static bool CheckBase64StringSafe(string param)
    {
        if (param == null)
        {
            // null string is not Base64 something
            return false;
        }

        // replace optional CR and LF characters
        param = param.Replace("\r", String.Empty).Replace("\n", String.Empty);

        if (param.Length == 0 ||
            (param.Length % 4) != 0)
        {
            // Base64 string should not be empty
            // Base64 string length should be multiple of 4
            return false;
        }

        // replace pad chacters
        int lengthNoPadding = param.Length;
        int lengthPadding;

        param = param.TrimEnd(Base64Padding);
        lengthPadding = param.Length;

        if ((lengthNoPadding - lengthPadding) > 2)
        {
            // there should be no more than 2 pad characters
            return false;
        }

        foreach (char c in param)
        {
            if (Base64Characters.Contains(c) == false)
            {
                // string contains non-Base64 character
                return false;
            }
        }

        // nothing invalid found
        return true;
    }

我没有进行过广泛的代码测试,因此无法保证其功能!

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接