在 Java 中使用正则表达式进行 switch 语句

2022-01-19 00:00:00 regex switch-statement java
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.)

相关文章