从字符串中过滤掉非十六进制字符的更好方法是什么?

What would be a better way to filter out non-hexadecimal characters from a string?

我刚刚在我的 C# 项目上试用了 PVS-Studio,它指出了这个筛选有效十六进制字符的函数。最初逻辑允许所有字符,但在修复它之后我无法动摇有更好的方法来做到这一点的感觉。

    string ValidHex()
    {
        string str = foo.Value;
        for (int index = 0; index < str.Length; index++)
        {
            if (Char.IsDigit(str[index]) == false)
            {
                if ((str[index] >= 'A' && str[index] <= 'F') ||
                    (str[index] >= 'a' && str[index] <= 'f'))
                    continue;
                else
                    return "Invalid Hex value";
            }
        }
        return null;
    }

我知道我无法提高时间复杂度,但是有没有更简单的方法来筛选这些 ASCII 值?

检查字符串是否为有效的十六进制字符串的一种简单方法是使用十六进制正则表达式并尝试匹配它。

public bool OnlyHexInString(string test)
{
    // For C-style hex notation (0xFF) you can use @"\A\b(0[xX])?[0-9a-fA-F]+\b\Z"
    return System.Text.RegularExpressions.Regex.IsMatch(test, @"\A\b[0-9a-fA-F]+\b\Z");
}

在此处阅读更多内容:Check a string to see if all characters are hexadecimal values