Regex to match grades

2.7k Views Asked by At

I have an array

String[] grades = new String[]{"D","C-","C","C+","B-","B","B+","A-","A","A+"};

I want to check if a string is one of these values.

I could loop through the array to accomplish this, but I want to do it through regex.

1

There are 1 best solutions below

4
Sergey Kalinichenko On BEST ANSWER

The regex is rather simple:

[A-C][+-]?|D

The first part says that A through C could be followed by an optional plus or minus; the second part allows a D by itself.

I could loop through the array to accomplish this

You could also use contains(), to do it without a loop:

if (Arrays.asList(grades).contains(grade)) {
    ...
}