2014-02-06 20 views
-1
序列的高端測試正則表達式

比方說,可能表達的值是這樣的:的Python:對結果

a) 10-15 of 25 results 
b) 20-25 of 25 results 
c) 1,220 - 1,240 of 1300 results 
d) 1,280 - 1,300 of 1300 results 

我要測試的表達,使得b和d將返回true和A和C會返回false。換句話說,我正在尋找序列條件的結束。

+4

而且您已嘗試? – Jerry

回答

1

感謝Pykler指着我在正確的方向。答案必須考慮到逗號,所以我已經對逗號進行了以下修改以適應他的回答:

def is_end(s) : 
    end_re = re.compile(r'([\d]*,?[\d]*) of \1 results')  
    return bool(end_re.search(s)) 
1

這應該做的伎倆:

end_re = re.compile(r'([\d,]+) of \1 results') 
def is_end(s): 
    return bool(end_re.search(s)) 

的想法是找到在結果的最後部分相同的數字。 See this answer for more info

編輯:固定由提問者

+0

我喜歡簡單,但由於數字中的逗號而失敗。即mystring =「234 - 1,250個1,250個結果」返回false。但它確實工作的地方沒有號碼 –

+0

修正它,謝謝你的答案...你的答案也應該工作,唯一的小問題是答案中的整個數字組是可選的,所以你的正則表達式可能與羣組。然而,默認情況下,正則表達式是貪婪的,所以如果你的輸入正是你總是描述的東西,那麼你的答案就會起作用。 – Pykler

0

此作品中提到的逗號問題 -

input = ''' 
a) 10-15 of 25 results 
b) 20-25 of 25 results 
c) 1,220 - 1,240 of 1300 results 
d) 1,280 - 1,300 of 1300 results 
''' 

import re 
regex = r'([0-9\,]+)[ ]*\-[ ]*([0-9\,]+)[ ]+of[ ]+([0-9]+)' 
for ip in input.split("\n"): 
    matches = re.findall(regex, ip) 
    if matches and len(matches[0]) == 3: 
     r = int(matches[0][1].replace(",","")) 
     results = int(matches[0][2]) 
     if(r == results): 
      print "true" 
     else: 
      print "false" 

'''OUTPUT: 
false 
true 
false 
true 
'''