2010-05-09 62 views
1

在Rubular,我创建了一个正则表达式:Python和Rubular之间的正则表达式的区别?

推荐:良好的舒适性水平的计算机和一些艺术

(Prerequisite|Recommended): (\w|-|)* 

它粗体显示的一致。

夏天。 2学分。 先决条件: 预大一新生或 指导老师的许可。信用可能不适用于工程学位 。仅限S-U 等级。

这里是Python中使用正则表达式的:

note_re = re.compile(r'(Prerequisite|Recommended): (\w|-|)*', re.IGNORECASE) 

def prereqs_of_note(note): 
    match = note_re.match(note) 
    if not match: 
     return None 
    return match.group(0) 

不幸的是,代码返回None,而不是一场比赛:

>>> import prereqs 

>>> result = prereqs.prereqs_of_note("Summer. 2 credits. Prerequisite: pre-fres 
hman standing or permission of instructor. Credit may not be applied toward engi 
neering degree. S-U grades only.") 

>>> print result 
None 

什么我错在这里做什么?

更新:我需要re.search()而不是re.match()吗?

+2

http://pythex.org/说,即使使用Python的引擎,正则表达式匹配该字符串,所以问题是你如何使用正则表达式(我不知道Python) – Gareth 2010-05-09 22:32:59

+1

此外,个人我会将你的正则表达式更新为'(先决条件|推荐):([\ w - ] *)',这样你可以更好地捕获剩余的比赛。 (见http://rubular.com/r/5v7u66vc1M) – Gareth 2010-05-09 22:35:26

回答

2

您想使用re.search(),因为它扫描字符串。您不需要re.match(),因为它试图在字符串的开头应用该模式。

>>> import re 
>>> s = """Summer. 2 credits. Prerequisite: pre-freshman standing or permission of instructor. Credit may not be applied toward engineering degree. S-U grades only.""" 
>>> note_re = re.compile(r'(Prerequisite|Recommended): ([\w -]*)', re.IGNORECASE) 
>>> note_re.search(s).groups() 
('Prerequisite', 'pre-freshman standing or permission of instructor') 

此外,如果您想要匹配“instructor”之后的第一个句点,则必须添加一个文字'。'。到你的模式:

>>> re.search(r'(Prerequisite|Recommended): ([\w -\.]*)', s, re.IGNORECASE).groups() 
('Prerequisite', 'pre-freshman standing or permission of instructor. Credit may not be applied toward engineering degree. S-U grades only.') 

我建议你让你的模式贪婪和匹配上线的其余部分,除非那不是你真正想要的东西,虽然它看起来像你一样。

>>> re.search(r'(Prerequisite|Recommended): (.*)', s, re.IGNORECASE).groups() 
('Prerequisite', 'pre-freshman standing or permission of instructor. Credit may not be applied toward engineering degree. S-U grades only.') 

先前图案与另外的文字“”,返回相同.*这个例子。

+1

......或者可能是'(。*?\。)'仅匹配到第一个时间段。 – 2010-05-10 08:38:54