Using regex for switch-statement in Java(在 Java 中使用正则表达式进行 switch 语句)
问题描述
void menu() {
print();
Scanner input = new Scanner( System.in );
while(true) {
String s = input.next();
switch (s) {
case "m": print(); continue;
case "s": stat(); break;
case "[A-Z]{1}[a-z]{2}\d{1,}": filminfo( s ); break;
case "Jur1": filminfo(s); break; //For debugging - this worked fine
case "q": ; return;
}
}
}
似乎我的正则表达式已关闭,或者我没有在案例陈述中正确使用它.我想要的是一个字符串: 以一个大写字母开头,后跟两个小写字母,后跟至少一个数字.
It seems like either my regex is off or that I am not using it right in the case-statement. What I want is a string that: Begins with exactly one uppercase letter and is followed by exactly two lowercase letters, which are followed by at least one digit.
我检查了正则表达式 API 并尝试了三种变体(贪婪、不情愿和所有格量词),但不知道它们的正确用途.还检查了 String 的方法,但没有找到与我的需求相关的方法.
I've checked out the regex API and tried the three variants (greedy, reluctant and possessive quantifiers) without knowing their proper use. Also checked the methods for String without finding a method that seemed pertinent to my needs.
推荐答案
您不能将正则表达式用作 switch case.(想想看:Java 怎么知道你是想匹配字符串 "[AZ]{1}[az]{2}\d{1,}"
还是正则表达式?)
You can't use a regex as a switch case. (Think about it: how would Java know whether you wanted to match the string "[A-Z]{1}[a-z]{2}\d{1,}"
or the regex?)
在这种情况下,您可以做的是尝试匹配默认情况下的正则表达式.
What you could do, in this case, is try to match the regex in your default case.
switch (s) {
case "m": print(); continue;
case "s": stat(); break;
case "q": return;
default:
if (s.matches("[A-Z]{1}[a-z]{2}\d{1,}")) {
filminfo( s );
}
break;
}
(顺便说一句,这只适用于 Java 7 及更高版本.在此之前没有切换字符串.)
(BTW, this will only work with Java 7 and later. There's no switching on strings prior to that.)
这篇关于在 Java 中使用正则表达式进行 switch 语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 Java 中使用正则表达式进行 switch 语句


- Java包名称中单词分隔符的约定是什么? 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01