C# 判断是不是合法的16进制字符串
方法一:用正则表达式判断,代码如下:
public const string PATTERN = @"([^A-Fa-f0-9]|\s+?)+"; /// <summary> /// 判断十六进制字符串hex是否正确 /// </summary> /// <param name="hex">十六进制字符串</param> /// <returns>true:不正确,false:正确</returns> public bool IsIllegalHexadecimal(string hex) { return System.Text.RegularExpressions.Regex.IsMatch(hex, PATTERN); }
线性遍历输入的十六进制字符串中是否包含非十六进制字符,代码如下:方法二:
public IList<char> HexSet = new List<char>() { '0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','a','b','c','d','e','f' }; /// <summary> /// 判断十六进制字符串hex是否正确 /// </summary> /// <param name="hex">十六进制字符串</param> /// <returns>true:不正确,false:正确</returns> public bool IsIllegalHexadecimal(string hex) { foreach (char item in hex) { if (!HexSet.Contains<char>(item)) return true; } return false; }
通过调用上述方法就可以清楚的知道输入的十六进制字符是否正确,然后为程序的下一个工作提供条件。
还有一种方法性能比较慢 就放到文章最后面了
/// <summary> /// 判断是否为合法的16进制字符串 /// </summary> /// <param name="hexString"></param> /// <returns></returns> public bool IsHexadecimal(string hexString) { try { hexString = hexString.Replace(" ", "").Replace("\r", "").Replace("\n", ""); if ((hexString.Length % 2) != 0) hexString += " "; byte[] returnBytes = new byte[hexString.Length / 2]; for (int i = 0; i < returnBytes.Length; i++) returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16); } catch { return false; } return true; } #endregion