Python和Rubular之间正则表达式的区别?

时间:2010-05-09 22:24:31

标签: python regex rubular

在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()吗?

1 个答案:

答案 0 :(得分: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')

另外,如果你想匹配“讲师”这个词之后的第一个句号,你将不得不添加一个文字“。”进入你的模式:

>>> 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.')

上一个添加了文字“。”的模式,在此示例中返回与.*相同的内容。

相关问题