2012-05-18 21 views
0
import re 

cards1 = "'F'*4 + 'H'*10"; cards2 = 'FFHH' 
def find_number_of_cards(cards): 
    regexp = re.compile(r"(?P<FandH>[FH]+) | (('F')[*](?P<F>[0-9]+)\s*[+]\s*('H')[*](?P<H>[0-9]+))") 
    result = regexp.search(cards) 
    if result == None: 
     return ("The expression given is not valid.") 
    else: 
     FnH = result.group('FandH') 
     F = result.group('F') 
     H = result.group('H') 
     if FnH == None: 
      return F, H 
     else: 
      return "Blank." 

print(find_number_of_cards(cards1)) 
print(find_number_of_cards(cards2)) 
+0

什麼是卡的定義 - >沒有人可以在不知道什麼是卡的情況下幫助reg-ex。 「find_number_of_cards(cards1)」和「find_number_of_cards(cards2)」的預期輸出是什麼? –

回答

3

更改此:

regexp = re.compile(r"(?P<FandH>[FH]+) | (('F')[*](?P<F>[0-9]+)\s*[+]\s*('H')[*](?P<H>[0-9]+))") 

這樣:

regexp = re.compile(r"(?P<FandH>[FH]+)|(('F')[*](?P<F>[0-9]+)\s*[+]\s*('H')[*](?P<H>[0-9]+))") 

它尋找字符串中的空間,這不在那裏。

+0

這工作得很好,謝謝。 –

相關問題