十六进制范围模式匹配

时间:2018-08-17 22:50:51

标签: c# regex

我正在使用以下代码段将十六进制数字与范围匹配,但没有一个匹配。后来我也转换为十进制,现在很明显正则表达式是错误的。一些提示会很好。

        string[] tests = {"F200", "F201", "F2FF","F100","FFFF"};

        const string regexPattern = @"\b[\uF200-\uF2FF]\b";

        Regex rx = new Regex(regexPattern,RegexOptions.Compiled | RegexOptions.IgnoreCase);


        foreach (string test in tests)
        {
            if(rx.IsMatch(test))
                Console.WriteLine("{0} is within the range.",test);
            else
                Console.WriteLine("{0} is not within the range.",test);
        }

        foreach(string test in tests)
        {
            Console.WriteLine("The corresponding decimal value of " + test + " is: " + int.Parse(test, System.Globalization.NumberStyles.HexNumber));
        }

我从regex pattern for a range and above 127 中找到了提示,但这并不能解决问题

2 个答案:

答案 0 :(得分:3)

要以字符串形式获取F200 - F2FF的十六进制范围,则需要此正则表达式。

[fF]2[0-9a-fA-F]{2}

答案 1 :(得分:0)

如sln所述,在他的评论中,您正在将字符串与Unicode字符进行比较。

通过将字符串数组更改为: string[] tests = {"\uF200", "\uF201", "\uF2FF", "\uF100", "\uFFFF"};

而且,您的正则表达式类似:const string regexPattern = @"[\uF200-\uF2FF]";

将结果代码留给您:

    string[] tests = {"\uF200", "\uF201", "\uF2FF", "\uF100", "\uFFFF"};

    const string regexPattern = @"[\uF200-\uF2FF]";

    Regex rx = new Regex(regexPattern,RegexOptions.Compiled | RegexOptions.IgnoreCase);


    foreach (string test in tests)
    {
        if(rx.IsMatch(test))
            Console.WriteLine("{0} is within the range.",test);
        else
            Console.WriteLine("{0} is not within the range.",test);
    }

    foreach(string test in tests)
    {
        Console.WriteLine("The corresponding decimal value of " + test + " is: " + int.Parse(test, System.Globalization.NumberStyles.HexNumber));
    }