Your regex isn't quite right.
When you write: [RQrq1-6]*
You're saying match zero or more repetitions of any character in the square brackets...
Try this [RQrq1-6]
- which means match exactly one.
I wrote a little "spike" program:
import java.util.regex.Pattern;
public class Spike {
public static void main(String[] args) {
testIt("Q");
testIt("q");
testIt("z");
testIt("Z");
testIt("R");
testIt("r");
testIt("0");
testIt("1");
testIt("2");
testIt("3");
testIt("4");
testIt("5");
testIt("6");
testIt("7");
testIt("02");
testIt("11");
testIt("17");
testIt(""); // should fail, used to pass with the question's regex
}
public static void testIt(String sample) {
System.out.print(sample+" ");
if (Pattern.matches("[RQrq1-6]*", sample)) {
System.out.println("match");
} else {
System.out.println("fail");
}
}
}
Output was this:
Q match
q match
z fail
Z fail
R match
r match
0 fail
1 match
2 match
3 match
4 match
5 match
6 match
7 fail
02 fail
11 match
17 fail
match
Having removed the star in the regex:
Q match
q match
z fail
Z fail
R match
r match
0 fail
1 match
2 match
3 match
4 match
5 match
6 match
7 fail
02 fail
11 fail
17 fail
fail
How to ignore the blanks
Substitute this version of testit:
public static void testIt(String sample) {
System.out.print(sample+" ");
Pattern pattern = Pattern.compile("\\s*([RQrq1-6])\\s*");
Matcher matcher = pattern.matcher(sample);
if (matcher.matches()) {
System.out.println("match '"+matcher.group(1)+"'");
} else {
System.out.println("fail");
}
}
Here are the critical lines of the output:
testIt(" 6");// ignore space tests
testIt(" 7");// ignore space tests
testIt("6 ");// ignore space tests
testIt("7 ");// ignore space tests
6 match '6'
7 fail
6 match '6'
7 fail
It uses a concept called a "capture group". A capture group is a section of a regex which is assigned a number so that the specific string of symbols that matched can be extracted. We're using a capture group here to pull the symbol out from the optional whitespace.