我们正在为我们的学校项目制作一个LolCode口译员。我们在编译解释器的词法分析器时遇到了麻烦。
// I HAS A <variable>
if(/(I\sHAS\sA)\s[a-zA-Z_$][0-9a-zA-Z_$]*$/i.test(entry)){
if(/(I\sHAS\sA)\s[a-zA-Z_$][0-9a-zA-Z_$]*/i.test(entry)){
var desc = "Variable Declaration";
var lex = /I\sHAS\sA/i.exec(entry);
$('#lexemes tbody').append('<tr><td>' + lex + '</td><td>' + desc + '</td></tr>');
}
if(/(I\sHAS\sA)\s[a-zA-Z_$][0-9a-zA-Z_$]*/i.test(entry)){
var string = /(I\sHAS\sA)\s[a-zA-Z_$][0-9a-zA-Z_$]*/i.exec(entry);
var desc = "Variable name";
var lex = /[^(I\sHAS\sA)\s]+/.exec(string);
$('#lexemes tbody').append('<tr><td>' + lex + '</td><td>' + desc + '</td></tr>');
}
}
// I HAS A <variable> ITZ <value>
if(/(I\sHAS\sA)\s[a-zA-Z_$][0-9a-zA-Z_$]*\sITZ\s.*/i.test(entry)){
if(/(I\sHAS\sA)\s[a-zA-Z_$][0-9a-zA-Z_$]*\sITZ\s.*/i.test(entry)){
var desc = "Variable Declaration";
var lex = /I\sHAS\sA/i.exec(entry);
$('#lexemes tbody').append('<tr><td>' + lex + '</td><td>' + desc + '</td></tr>');
}
if(/(I\sHAS\sA)\s[a-zA-Z_$][0-9a-zA-Z_$]*\sITZ\s.*/i.test(entry)){
var string = /(I\sHAS\sA)\s[a-zA-Z_$][0-9a-zA-Z_$]*\sITZ\s.*/i.exec(entry);
var desc = "Variable name";
var lex = /[^(I\sHAS\sA)\s]+/.exec(string);
$('#lexemes tbody').append('<tr><td>' + lex + '</td><td>' + desc + '</td></tr>');
}
if(/.+ITZ\s.*/i.test(entry)){
var string = /.+ITZ\s.*/i.exec(entry);
var desc = "Initialization";
var lex = /ITZ/i.exec(string);
$('#lexemes tbody').append('<tr><td>' + lex + '</td><td>' + desc + '</td></tr>');
}
}
&#13;
它工作正常,但我的变量名的正则表达式是错误的。我是regex的新手,所以任何帮助都会受到赞赏。
If the variable name has 'I' or 'HAS' or 'A', it's not caught by the regex.
我知道这是因为[^ ]
,但如果删除该部分,关键字I HAS A
将包含在变量名称中。请帮我改进我们的正则表达式。非常感谢你!