gpt4 book ai didi

c# - 如何在 C# 中测试一个字符串是否只包含十六进制字符?

转载 作者:行者123 更新时间:2023-11-30 13:51:55 27 4
gpt4 key购买 nike

我有一个很长的字符串(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;
}

最佳答案

另一种选择,如果您喜欢使用 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));
}

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

关于c# - 如何在 C# 中测试一个字符串是否只包含十六进制字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3670045/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com