Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to match grades

Tags:

java

regex

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.

like image 228
atripathi Avatar asked Dec 16 '22 14:12

atripathi


1 Answers

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)) {
    ...
}
like image 51
Sergey Kalinichenko Avatar answered Jan 02 '23 01:01

Sergey Kalinichenko