【问题标题】:Regular expression , must end with comma正则表达式,必须以逗号结尾
【发布时间】:2012-03-12 02:11:57
【问题描述】:

我正在尝试解析传入的指令。我想使用正则表达式来验证每个子字符串。 如何确保字符串以逗号结尾?我的内存正则表达式(mips)也不起作用。

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

        }

如何从内存中加载的示例

lw $t7,248($t2) 

【问题讨论】:

  • 为什么需要正则表达式? source.EndsWith(",") 会做你想做的事,而且很好读。
  • 我需要确保整个字符串适合表格。即临时 => $t0 - $t9
  • 请解释一下我如何确保字符串以逗号结尾? 作为您的示例lw $t7,248($t2) 末尾没有逗号。
  • @Borodin 每个操作数都以逗号结尾,除了最后一个。在该示例中,只有 2 个操作数,lw 考虑运算符并以不同方式处理
  • 那我觉得你应该用String.Split在逗号处分割操作数字符串,分别验证每一块。

标签: .net regex c#-4.0 mips


【解决方案1】:

我不确定您对以逗号结尾的字符串是什么意思。据我所知,你可以写@"\$t[0-9],"

您的内存正则表达式不匹配,因为您有[s-t]\b[0-9]。由于 s 和 t 以及 0 到 9 都是单词字符,因此它们之间不能有单词边界。你也有一个未转义的右括号。这个@"\d+\(\$[st][0-9]\)" 可以工作。

如果你的操作数列表只是用逗号分隔,那么用逗号分割字符串并验证每个

string command = "$t7,248($t2)";

string [] operands = command.Split(new Char [] {','});

你的正则表达式需要在开头和结尾锚定,像这样

if (Regex.IsMatch(source, @"^\$t[0-9]$"))
    return OperandType.Temporary;
if (Regex.IsMatch(source, @"^\$s[0-9]$"))
    return OperandType.Store;

等等。

【讨论】:

  • 感谢第一个不起作用,但他的记忆正则表达式起作用。我决定在测试正则表达式之前检查它是否以逗号结尾。这也将更容易排除最后一个参数。谢谢
【解决方案2】:

这个表达式可能有效:

,$

【讨论】:

  • 没用。试过 @"\$t[0-9],$" 不确定你的意思
  • 尝试转义逗号。 "\$t[0-9]\,$"
  • 逗号不是正则表达式元字符,不需要转义。我认为问题在于逗号不在字符串的末尾。
猜你喜欢
  • 1970-01-01
  • 2023-03-15
  • 2020-03-28
  • 1970-01-01
  • 1970-01-01
  • 2016-01-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多