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.
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 .
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.
$ means "Match the end of the string" (the position after the last character in the string).
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With