gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 06:16:56 24 4
gpt4 key购买 nike

在 Rubular 中,我创建了一个正则表达式:

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

它与粗体匹配:

Recommended: good comfort level with computers and some of the arts.

Summer. 2 credits. Prerequisite: pre-freshman standing or permission of instructor. Credit may not be applied toward engineering degree. S-U grades only.

以下是 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() 吗?

最佳答案

您想要使用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.')

前面的模式添加了文字“.”,返回的结果与本示例中的 .* 相同。

关于python - Python 和 Rubular 之间正则表达式的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2799418/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com