在Java中使用regex for switch-statement [英] Using regex for switch-statement in Java

查看:89
本文介绍了在Java中使用regex for switch-statement的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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.

推荐答案

你不能使用正则表达式作为开关盒。 (想一想: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中使用regex for switch-statement的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆