你爲什麼要使用正則表達式來實現紙牌遊戲的邏輯是什麼?看起來很瘋狂......但它可以完成!
s.matches("([123456789TJQKA])([dchs])\\1(?!\\2)[dchs]|([123456789TJQKA])\\3")
這是一個測試,以驗證它是否工作正常(它也記錄了有關您還沒有涵蓋在你的問題的特殊情況下,我的假設):
public class Test
{
private static void test(String input, boolean expected)
{
boolean result = input.matches("([123456789TJQKA])([dchs])\\1(?!\\2)[dchs]|([123456789TJQKA])\\3");
if (result != expected)
throw new RuntimeException("Failed!");
}
public static void main(String[] args) throws Exception
{
test("JJ", true);
test("JsJd", true);
test("11", true);
test("2c2h", true);
test("Js", false);
test("JsJs", false);
test("JsJ", false);
test("JQ", false);
test("1d1d", false);
test("J", false);
test("", false);
test("3d3d", false);
test("JsJdJ", false);
test("JsJdJh", false);
test("1A", false);
}
}
是否重複檢測有在正則表達式中完成?爲什麼不先解析卡對象然後檢查它們是否相等? – finnw 2010-02-08 22:50:58
我在想同樣的事情......但我認爲使用正則表達式來處理整個事情是「更清潔」的。否則,我只是開始有「其他 - 如果」遍佈整個地方:) – 2010-02-08 22:59:15
這些卡片是否總是按預定順序列出?或者同一隻手可以用'Ac5JsJh'或'JhAcJs5'或其他什麼來表示?另外,我注意到你將'1'和'A'匹配爲卡片值;那些都不是指Ace? – 2010-02-09 01:07:08