求一个正则表达式,能验证十六进制数,并自动纠正错误(不是屏蔽错误然后返回的那种),
比如我发送一个十六进制数:adt 12 ce 63 02251 2634
然后经过正则表达式纠正后 :AD 12 CE 63 02 25 01 26 34
请教高手,正则表达式怎么表达正则表达式

解决方案 »

  1.   

    void Main()
    {
    string str="adt 12 ce 63 02251 2634";
    str=Regex.Replace(Regex.Replace(str,@"(?i)[^a-f\d\s]+",""),"\\w{3,}",
    m=>string.Join(" ",Regex.Split(m.Value,@"(?<=\G\w{2})(?!$)").Select(x=>x.PadLeft(2,'0')).ToArray())).ToUpper();
    Console.WriteLine(str); //AD 12 CE 63 02 25 01 26 34}
      

  2.   


    错误 1 无法将 lambda 表达式 转换为类型“string”,因为它不是委托类型 C:\Documents and Settings\Administrator\桌面\测试\SerialportSample(1)+2008\SerialportSample\SerialportSample\Form1.cs 161 37 SerialportSample错误 2 “string[]”不包含“Select”的定义,并且找不到可接受类型为“string[]”的第一个参数的扩展方法“Select”(是否缺少 using 指令或程序集引用?) C:\Documents and Settings\Administrator\桌面\测试\SerialportSample(1)+2008\SerialportSample\SerialportSample\Form1.cs 161 59 SerialportSample
      

  3.   


    //.NET FREAMEWORK3.5+版本 编译通过
    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Text.RegularExpressions;
    using System.Linq;namespace ConsoleApplication2
    {
        class Program
        {
            static void Main(string[] args)
            {
                string str = "adt 12 ce 63 02251 2634";
                str = Regex.Replace(Regex.Replace(str, @"(?i)[^a-f\d\s]+", ""), "\\w{3,}",
                                        m=> string.Join(" ", Regex.Split(m.Value, @"(?<=\G\w{2})(?!$)").Select(x => x.PadLeft(2, '0')).ToArray())).ToUpper();
                Console.WriteLine(str); //AD 12 CE 63 02 25 01 26 34
                Console.ReadKey();
            }
        }
    }