Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using regex for switch-statement in Java

Tags:

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.

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.

like image 693
jollyroger Avatar asked Nov 11 '11 00:11

jollyroger


People also ask

Can I use regex in switch case?

RegExp can be used on the input string with the match method too. To ensure that we have a match in a case clause, we will test the original str value (that is provided to the switch statement) against the input property of a successful match .

Which Java version allows pattern matching in switch?

The Java SE 17 release introduces pattern matching for switch expressions and statements (JEP 406) as a preview feature. Pattern matching provides us more flexibility when defining conditions for switch cases.

What does '$' mean in regex?

$ means "Match the end of the string" (the position after the last character in the string).


1 Answers

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;     } 

(BTW, this will only work with Java 7 and later. There's no switching on strings prior to that.)

like image 195
cHao Avatar answered Sep 29 '22 20:09

cHao