我正在写一个汇编程序,它分析汇编代码并生成目标代码。但是,我遇到了一些关于regex函数的问题。我没有使用java正则表达式的经验,所以我不太确定我在做什么来引起这个异常。下面是抛出异常的函数。要计算的THe第一个操作数是"0",它当然应该计算为false。
//Returns true if operand is a Symbol, false otherwise.
public boolean isSymbol(String operand){
if(!operand.equals("")){
if(((operand.matches("[a-zA-Z]*"))&&
(!operand.matches(".'"))) ||(operand.matches("*"))){ //Exception
return true;
}
else return false;
}
return false;
}发布于 2012-12-03 12:40:59
我认为您的问题在于*表达式。java regexpx中的*本身是没有意义的,它必须遵循一些其他的东西(它意味着“零次或多次”)。如果您想要文字模式,您需要对其进行转义- \\*这里是javadoc \\* Pattern,它列出了选项http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html
发布于 2012-12-03 12:47:25
operand.matches("*")matches采用正则表达式的字符串表示形式,而'*‘不是有效的正则表达式。对于长长的正则表达式简介,您可以查看这里:http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html
在正则表达式中,'*‘字符表示“匹配前一项0次或更多次”。例如:
"a".matches("a*") // is true
"aaaaaaa".matches("a*") // is true
"aaaaaab".matches("a*b") // is true如果要匹配输入字符串中的文字'‘字符,则必须转义正则表达式中的'’,如下所示:
operand.matches("\\*")然后
"a*".matches("a\\*") // is true
"*".matches("\\*") // is true
"aaaa*b".matches("a*\\*b") // is true
"0".matches("\\*") // is false, which I think is what you want.发布于 2012-12-03 14:00:22
尝试替换if条件,如下所示:
if(((operand.matches("[a-zA-Z]+")) && !operand.matches(".'")))){`enter code here`这里+表示1或更多,这确保oprand中至少有一个a-z或A-Z。
https://stackoverflow.com/questions/13677208
复制相似问题