收到一个串口的字符串,需要进行匹配,格式如下:
"AT^CKPD=para1,para2"para1:单字符
para2:数值,可能占1到3位,这个参数是可选的,如果没有的话,参数前的逗号也不存在这个字符串前后可能会有其他一些无意义的字符串,例如:"informationAT^CKPD=para1,para2OK",需要将前后部分忽略,只匹配中间那段。我匹配字符串的代码如下:
string ATCmdPattern = @"^*AT^KREC=(?<key>\w+)?,(?<time>\d+)";
Regex ATCmdExpression = new Regex(ATCmdPattern, RegexOptions.Compiled);
if (!Regex.IsMatch(RecvMessage, ATCmdPattern)) return;
Match ATCmdMatch = ATCmdExpression.Match(RecvMessage);
if(ATCmdMatch.Groups["time"].Value.Length > 0)
    m_time = ATCmdMatch.Groups["key"].Value;
m_key = ATCmdMatch.Groups["key"].Value;正则表达式写的不对,所以匹配不上,请高手指点,谢谢!

解决方案 »

  1.   


    string ATCmdPattern = @"AT\^CKPD=(?<key>\w+)(,(?<time>\d+))*"; 
    Regex ATCmdExpression = new Regex(ATCmdPattern, RegexOptions.Compiled); 
    if (!Regex.IsMatch(RecvMessage, ATCmdPattern)) return; 
    Match ATCmdMatch = ATCmdExpression.Match(RecvMessage); 
    if(ATCmdMatch.Groups["time"].Value.Length > 0) 
        m_time = ATCmdMatch.Groups["key"].Value; 
    m_key = ATCmdMatch.Groups["key"].Value;