代码之家  ›  专栏  ›  技术社区  ›  JYelton Melchior Blausand

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

  •  2
  • JYelton Melchior Blausand  · 技术社区  · 14 年前

    我有一个长字符串(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;
    }
    
    3 回复  |  直到 14 年前
        1
  •  3
  •   SLaks    14 年前

    你误解了 Multiline option :

    使用多行模式,其中 ^ $ 匹配每行的开始和结束(而不是开始 和输入字符串的结尾)。

    把它改成

    static readonly Regex r = new Regex(@"^[0-9A-F\r\n]+$");
    public static bool VerifyHex(string _hex)
    {
        return r.Match(_hex).Success;
    }
    
        2
  •  5
  •   Jon Skeet    14 年前

    另一个选项,如果您喜欢使用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
    }
    

    或:

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

    我认为在这种情况下,regex可能是更好的选择,但我只是想提一下linq,出于兴趣:)

        3
  •  1
  •   Kelsey    14 年前

    已经有一些很好的答案,但是没有人提到使用内置解析,这似乎是最直接的方法:

    public bool IsHexString(string hexString)
    {
        System.Globalization.CultureInfo provider = new System.Globalization.CultureInfo("en-US");
        int output = 0;
        return Int32.TryParse(hexString, System.Globalization.NumberStyles.HexNumber, provider, out output))
    }