Reputation: 519
I have the following expression representing a playing card pattern:
String RCARD1 = "[CDHS]{1}\\:\\d{1,2}[1-14]";
when I test it in my test case it works as expected, here is the test case:
@Test
public void checkRegex() throws AssertionError {
System.out.println("Checking the correctness of card regular expressions");
String RCARD1 = "[CDHS]{1}\\:\\d{1,2}[1-14]";
String cardSymbol = "H:14";
assertTrue(cardSymbol.matches(RCARD1));
cardSymbol = "C:16";
assertFalse(cardSymbol.matches(RCARD1));
cardSymbol = "Z:5";
assertFalse(cardSymbol.matches(RCARD1));
}
However when I use this into the Card constructor it always returns false. The following code is slightly modified and I don't check the result, further decipher method works fine.
public Card(String cardSymbol) throws UnknownCardException {
boolean res = cardSymbol.matches(RCARD1); //fails here !!!
if (this.decypherCard(cardSymbol)) {
}
else throw new UnknownCardException();
}
So what's the problem here? Why it is not working?
Upvotes: 1
Views: 62
Reputation: 627082
The [1-14]
character class matches 1
and 4
only. If you need to match numbers from 1
to 14
, use (?:1[0-4]|0?[1-9])
.
This regex should work then:
^[CDHS]:(?:1[0-4]|0?[1-9])$
See this demo.
NOTE: With String.matches()
, you do not need ^
and $
(you may remove them from the pattern).
Upvotes: 3