2012-03-09 27 views
1

我试图创建一个方法,它根据正则表达式检查一个字符串并返回一个寄存器类型(mips)。问题是,我似乎无法创建正确的正则表达式。 请看看并提出建议。由于正则表达式解析器的问题

public static RegisterType CheckRegex(this string source) 
     { 
      var tempMatch = new Regex("$t0|$t1|$t2|$t3|$t4|$t5|$t6|$t7|$t8|$t9|").Match(source); //$t0 - $t9 
      if(tempMatch.Length == source.Length) 
       return RegisterType.Temporary; 
      var storeMatch = new Regex(@"(^\$s)+[0-9]").Match(source); //$s0 - $s9 
      if (storeMatch.Length == source.Length) 
       return RegisterType.Store; 
      var reservedMatch = new Regex(@"").Match(source);   //$k0 - $k1 
      if (reservedMatch.Length == source.Length) 
       return RegisterType.OSReserved; 
      var constantMatch = new Regex(@"0-9").Match(source);  //Any integer 
      if (constantMatch.Length == source.Length) 
       return RegisterType.Constant; 
      var memoryMatch = new Regex("").Match(source); 
      if (memoryMatch.Length == source.Length) 
       return RegisterType.Memory; 

      return RegisterType.Invalid; 
     } 

UPDATE:现在一切工作正常,但不包括我的记忆正则表达式

public static RegisterType GetRegisterType(this string source) 
     { 
      if (Regex.IsMatch(source, @"\$t[0-9]")) 
       return RegisterType.Temporary; // $t0 - $t9 
      if (Regex.IsMatch(source, @"\$s[0-9]")) 
       return RegisterType.Store; // $s0 - $s9 
      if (Regex.IsMatch(source, @"\$k[0-1]")) 
       return RegisterType.OSReserved; // $k0 - $k1 
      if (Regex.IsMatch(source, @"[-+]?\b\d+\b")) 
       return RegisterType.Constant; 
      if (Regex.IsMatch(source, @"\$zero")) 
       return RegisterType.Special; 
      if (Regex.IsMatch(source, @"[a-zA-Z0-9]+\b\:")) 
       return RegisterType.Label; 
      if (Regex.IsMatch(source, @"\d+\b\(\$[s-t]\b[0-9])")) 
       return RegisterType.Memory; 
      return RegisterType.Invalid; 

     } 
+1

什么部分回事?你在哪里不匹配。注意,我相信你需要在临时寄存器匹配表达式 – pstrjds 2012-03-09 18:15:07

+0

中转义'$'我还有一个问题(因为我写MIPS汇编已经有多年了),你的源代码是一个完整的指令吗?您的匹配k个寄存器的表达式是空白的?你的匹配“记忆”表达式也是一个空白的正则表达式。你可以给一些'source'的例子吗? – pstrjds 2012-03-09 18:23:11

+0

@pstrjds参考内存例如:lw $ t7,248($ t2) – 2012-03-09 19:46:55

回答

3

正如其他人所说的,您需要在"$t0|$t1|$t2|$t3|$t4|$t5|$t6|$t7|$t8|$t9|"之前加上反斜杠以避开美元符号。此外,您可以更简洁地编写为@"\$t[0-9]"。这将匹配一个美元符号,然后是't'后跟一个数字。你有一个尾随的管道字符,后面什么也没有,可以删除。

+1

实际上,末尾的'|'*必须被移除。有了它,正则表达式可以合法地匹配任何东西,就好像你用圆括号包装了它并添加了“?”量词。这意味着第一次测试总是会成功,其他测试都不会执行。您的简洁版本还可以纠正该错误。 – 2012-03-09 23:18:10

3

$是在正则表达式特殊字符,在该行的末尾匹配。如果您想匹配$文字,请使用转义(\$)

1

如果您source只是一个注册/存储位置,你也许可以简化这个东西到是这样的:

public static RegisterType CheckRegex(this string source) 
{ 
    if (Regex.IsMatch(@"\$\t\d")) return RegisterType.Temporary; // $t0 - $t9 
    if (Regex.IsMatch(@"\$\s\d")) return RegisterType.Store; // $s0 - $s9 
    if (Regex.IsMatch(@"\$\k\[0-1]")) return RegisterType.OSReserved; // $k0 - $k1 
    if (Regex.IsMatch(source, @"\d")) return RegisterType.Constant; 
    // Don't remember the pattern for Memory, if you post an update I can update this 

    return RegisterType.Invalid; 
}