我一直在尋找如何驗證base64字符串,並遇到此問題。驗證字符串是使用RegEx的base64格式?
^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$
我需要一點幫助,使其允許「==」和「=」。
謝謝
我一直在尋找如何驗證base64字符串,並遇到此問題。驗證字符串是使用RegEx的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;
}
}
我已經更新上面的代碼位,以滿足幾個要求:
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;
}
我沒有測試的代碼廣泛,所以根本沒有功能保證!
你是什麼意思? '=='和'='已經被允許。 – kennytm 2010-07-28 17:08:31
是的你的權利它的作品。對不起,我只是在我的編碼字符串中添加了一個額外的「=」來測試何時需要編寫包含「==」的新編碼字符串:) – arbme 2010-07-28 17:14:54
請注意加號需要轉義。像這樣:'^(?:[A-Za-z0-9 \ + /] {4})*(?:[A-Za-z0-9 \ + /] {2} == | [A-Za -z0-9 \ + /] {3} =)?$' – 2018-02-04 23:53:29