英文:
Reverse Polish notation in Java. Checking for any symbols or characters (regex), that should not be in a string array
问题
我正在尝试弄清楚为什么这段代码不起作用,因为表示法 "156 154 152 - 3 + -" 应该可以正常运行而不抛出异常。在这种情况下,也许有更好的方法来使用正则表达式吗?当我实际运行我的解释函数而不手动抛出异常时,结果是正确的,一切都很好。但是对于这个练习,有一个对这种异常处理的要求。
下面是代码:
public class RegexTest {
public static void main(String[] arg) {
boolean b = check_notation("156 154 152 - 3 + -");
System.out.println(b);
}
public static boolean check_notation(String pol){
pol = pol.trim();
String[] tokens = pol.split("\\s+");
for (String r : tokens) {
if (!(r.matches("-[0-9]*") || r.matches("[0-9]*") || r.equals("/") || r.equals("*") || r.equals("-") || r.equals("+"))) {
throw new RuntimeException("存在不允许的符号。");
}
}
return true;
}
}
英文:
I'm trying to figure out why this piece of code is not working, as the notation "156 154 152 - 3 + -" should go through without throwing an exception. Is there maybe a better way to use regex in this case? When I actually run my interpret function without manually throeing the exception, the result is correct and all is good. But for this exercise, there is a requirement for such exception handling.
Here's the code:
public class RegexTest {
public static void main(String[] arg) {
boolean b = check_notation("156 154 152 - 3 + -");
System.out.println(b);
}
public static boolean check_notation(String pol){
pol = pol.trim();
String[] tokens = pol.split("\\s+");
for (String r : tokens) {
if (!(r.matches("-[0-9]*") || r.matches("[0-9]*") || r == "/" || r == "*" || r == "-" || r == "+")) {
throw new RuntimeException("There are symbols that are not allowed.");
}
}
return true;
}
}
答案1
得分: 1
@searchfind ... r.matches()对于特殊字符正则表达式的检查是必需的。另外,在 + 和 * 符号正则表达式之前加上 \\,以避免悬挂的元字符异常。<br>
请使用以下正则表达式条件:
if (!(r.matches("-[0-9]*") || r.matches("[0-9]*") || r.matches("/") ||
r.matches("\\*") || r.matches("-") || r.matches("\\+"))) {
throw new RuntimeException("不允许出现特殊符号。");
}
英文:
@searchfind ... r.matches() was required for the special characters regex check. Also; \\ needs to be prefixed before + and * symbol regex to avoid dangling meta character exceptions.<br>
Kindly use below Regex conditions
if (!(r.matches("-[0-9]*") || r.matches("[0-9]*") || r.matches("/") ||
r.matches("\\*") || r.matches("-") || r.matches("\\+"))) {
throw new RuntimeException("There are symbols that are not allowed.");
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论