继这个问题之后,在C#中编写Char.IsHex()函数的最佳方法是什么.到目前为止,我有这个,但不喜欢它:
bool CharIsHex(char c) {
c = Char.ToLower(c);
return (Char.IsDigit(c) || c == 'a' || c == 'b' || c == 'c' || c == 'd' || c == 'e' || c == 'f')
}
Run Code Online (Sandbox Code Playgroud) 我有一个长字符串(8000个字符),应该只包含十六进制和换行符.
验证/验证字符串是否包含无效字符的最佳方法是什么?
有效字符为:0到9和A到F.换行符应该是可接受的.
我从这段代码开始,但它无法正常工作(即当"G"是第一个字符时无法返回false):
public static bool VerifyHex(string _hex)
{
Regex r = new Regex(@"^[0-9A-F]+$", RegexOptions.Multiline);
return r.Match(_hex).Success;
}
Run Code Online (Sandbox Code Playgroud) 我有一个方法检查,如果一个字符串是一个有效的十六进制字符串:
public bool IsHex(string value)
{
if (string.IsNullOrEmpty(value) || value.Length % 2 != 0)
return false;
return
value.Substring(0, 2) == "0x" &&
value.Substring(2)
.All(c => (c >= '0' && c <= '9') ||
(c >= 'a' && c <= 'f') ||
(c >= 'A' && c <= 'F'));
}
Run Code Online (Sandbox Code Playgroud)
规则是:
表达式必须由偶数个十六进制数字组成(0-9,AF,af).
字符0x必须是表达式中的前两个字符.
我敢肯定它可以用更清洁,更有效的方式重写正则表达式.
你可以帮帮我吗?