When you use - in a character class expression, you allow the first character, the last character, and everything in between. Hence, A-C means 'A', 'B', or 'C'. If you want either 'A' or 'C', use [AC] instead:
string.matches(("^[AC]{3}$"))
Can I add a String or a char variable?
Yes, if you obey the general rules of character class expressions:
- If you have a
- or a ^ in your String, put them at the back
- If you have a
] or \ characters in your String, add an escape character in front of them.
Assuming that there are no special characters in your string, you can do
String str = "ac";
string.matches(("^[" + str + "]{3}$"))
^[ac]is a regex that matches a or c as the first character of the string. But you don't need a regex to do this.