如何测试字符串是否只包含C#中的十六进制字符?

JYe*_*ton 2 c# string validation

我有一个长字符串(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)

Jon*_*eet 5

另一种选择,如果您喜欢使用LINQ而不是正则表达式:

public static bool IsHex(string text)
{
    return text.All(IsHexChar); 
}

private static bool IsHexCharOrNewLine(char c)
{
    return (c >= '0' && c <= '9') ||
           (c >= 'A' && c <= 'F') ||
           (c >= 'a' && c <= 'f') ||
           c == '\n'; // You may want to test for \r as well
}
Run Code Online (Sandbox Code Playgroud)

要么:

public static bool IsHex(string text)
{
    return text.All(c => "0123456789abcdefABCDEF\n".Contains(c)); 
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下,我认为正则表达式可能是更好的选择,但我想提到LINQ为了感兴趣:)