I have the following switch statement.
switch (grade) {
case "a":
case "b":
case "c":
case "d":
case "a ":
case "b ":
case "c ":
case "d ":
case "a-":
case "b-":
case "c-":
case "d-":
case "e":
case "f":
case "i":
case "w":
case "z": {
return true;
}
}
return false;
I wanted to convert it to a regex statement. I was thinking of doing something similar, but is there a better way to allow a, A, b, B and b , B , a-, A- and etc?
The cases would be upper and lower, and only A-D will allow /-... everything else will fail.
CodePudding user response:
A pattern for those values, using a case insensitive match might be:
(?i)^(?:[a-d][ -]?|[efiwz])$
In parts, the pattern matches:
(?i)
Inline modifier for a case insensitive match^
Start of string(?:
Non capture group for the alternation|
[a-d][ -]?
Match a range a-d chars and optional-
|
Or[efiwz]
Matc any of the single listed chars
)
Close non capture group$
End of string
See a regex demo.
For example:
System.out.println("A".matches("(?i)^(?:[a-d][ -]?|[efiwz])$"));
System.out.println("x".matches("(?i)^(?:[a-d][ -]?|[efiwz])$"));
Output
true
false
For only the chars a-d in lower and uppercase:
(?i)^[a-d][ -]?$
CodePudding user response:
According to the description in the question:
The cases would be upper and lower, and only A-D will allow /-... everything else will fail.
A possibile pattern is
(([A-D]|[a-d])[ -]?)
If the correct scenario is instead what is written in your switch
statement, then The fourth bird's answer is indeed correct.