2016-08-11 41 views
1
pattern=''' 

^      #beginning of string 

M{0,3}    # thousands- 0 to 3 MS 

(CM|CD|D?C{0,3})    # hundreds - 900 (CM), 400 (CD), 0-300 (0 to 3 Cs), or 500-800 (D, followed by 0 to 3 Cs) 

(XC|XL|L?X{0,3})    # tens - 90 (XC), 40 (XL), 0-30 (0 to 3 Xs), or 50-80 (L, followed by 0 to 3 Xs) 

(IX|IV|V?I{0,3})    # ones - 9 (IX), 4 (IV), 0-3 (0 to 3 Is), or 5-8 (V, followed by 0 to 3 Is) 

$                   #end of string 
''' 

根据diveintopython3网站和我的逻辑,re.search(pattern,'M',re.VERBOSE)应该返回字符串匹配,但我没有返回时我输入call re.search。为什么是这样?为什么不是这个正则表达式工作?它应该基于diveintopython3

回答

0

它正常工作对我来说:

romanstring = "M" 
m = re.search(pattern, romanstring, re.VERBOSE) 
print(m.string) 

也许你是困惑,因为re.search返回一个“匹配对象”,而不是匹配的字符串直接返回。

+0

当我调用re.search时,虽然没有返回。甚至没有匹配对象 – HSCoder

+0

如果输入字符串不匹配正则表达式,它将返回None。但是,当我复制粘贴你提供的代码时,它工作得很好,无论是在Python3还是Python2中。 – hugomg

+0

我认为我的python存在问题 – HSCoder

相关问题