正则表达式:扑克手动解析器,N类

时间:2016-02-29 15:12:50

标签: python regex

我正在尝试编写一个regex来解析扑克牌: e.g:

4C 4H 6H 4D AH
4H 6H 4D 4C AH
4C 6H 4D AH 4H

我希望使用通用正则表达式来解析下面的每一行,如果它包含三次4则返回true。到目前为止,我从前一个关于sequence of repetition的问题中得到了什么,并没有考虑卡可以改组的事实。

到目前为止,我尝试的是:  4\w((?: \w{2})?(?: 4\w)){2} - 它涵盖了几个案例,但不是全部案例。请帮我解决这个问题。

已编辑:

def check_card_series(hand, range):
    #  4\w((?: \w{2})?(?: 4\w)){2}
    regexp = "%s\w((?: \w{2})?(?: %s\w)){%d}"
    result = False
    for card in cards:
        result = re.search(regexp % (card, card, range - 1), str(hand))
        if result:
            return result
    return result

我在regexp方法中使用Python。你能帮我分开一些东西,并向我展示一个更好的启发式做法。

4 个答案:

答案 0 :(得分:2)

我试着写regexp所以它可以解释自己:

four = r'4\w '
not_four = r'[^4]\w '
not_four_seq = r'(%s)*' % not_four
res = r'^%s(%s%s){3}$' % (not_four_seq, four, not_four_seq)
if re.match(res, '7C 4H 4H 5D 4H' + ' '):
    print 'OK'

答案 1 :(得分:1)

使用编程逻辑和正则表达式的组合:

import re

decks = ['4C 4H 6H 4D AH','4H 6H 4D 4C AH','4C 6H 4D AH 4H', '4C 4H 4D AH 4H']

rx = re.compile(r'4[A-Z]')
for deck in decks:
    matches = len(rx.findall(deck))
    if matches == 4:
        print deck
        # output: 4C 4H 4D AH 4H

如果4+letter恰好可以找到四次,则计算找到的匹配数并打印出实际的牌组。

答案 2 :(得分:0)

它只是打印手。使用这个approch

import re

test_str = "4C 4H 6H 4D AH\n4H 6H 4D 4C AH\n4C 6H 4D AH 4H\n6H 4D 6H 6H 6H"    
test_split = test_str.split("\n")

def check_hand(hand):
    p = re.compile(ur'(4\w).*(4\w).*(4\w)')
    result = re.match(p, hand)
    if result:
        return True

for hand in test_split:
    if check_hand(hand):
        print(hand)

答案 3 :(得分:0)

搜索一些简单的“手”的一般答案'尝试:

import re


hands = ['4C 4H 6H 4D AH','4H 6H 4D 4C AH','4C 6H 4D AH 4H','10C 10H JD AH 4H']
denom_list = ['2','3','4','5','6','7','8','9','10','J','Q','K','A']

for hand in hands:
    for denom in denom_list:
        regex = '({0}[HCDS])'.format(denom)
        match = re.findall(regex,hand)
        if len(match)==4:
            result = "Four of a kind: (4x{0})".format(denom)
        elif len(match)==3:
            result = "Three of a kind: (3x{0})".format(denom)
        elif len(match)==2:
            result = "Pair: (2x{0})".format(denom)
        elif len(match)==2:
            result = "High Card: (1x{0})".format(denom)
    print(hand,' -> ',result)