gpt4 book ai didi

python - 为什么我的带连字符的正则表达式不起作用?

转载 作者:太空宇宙 更新时间:2023-11-04 08:11:54 25 4
gpt4 key购买 nike

我正在使用 python 的 re 模块编写一个正则表达式来匹配简单的单词和单个带连字符的单词,例如:

test_case_input = """the wide-field infrared survey explorer is a nasa
infrared-wavelength space telescope in an earth-orbiting satellite which
performed an all-sky astronomical survey. be careful of -tricky tricky-
hyphens --- be precise."""

应该匹配:

test_case_output = ['the', 'wide-field', 'infrared', 'survey', 'explorer',
'is', 'a', 'nasa', 'infrared-wavelength', 'space', 'telescope', 'in', 'an',
'earth-orbiting', 'satellite', 'which', 'performed', 'an', 'all-sky',
'astronomical', 'survey', 'be', 'careful', 'of', 'tricky', 'tricky',
'hyphens', 'be', 'precise']

我找到了一个匹配单个带连字符的单词的正则表达式:r"[a-z]+-[a-z]+" 和另一个匹配简单单词的正则表达式 r"[a-z]+" 然后我尝试使用 an 或 r"[a-z]+-[a-z]+ | [a-z]+" 但输出是错误的:

[' wide', ' infrared', ' survey', ' explorer', ' is', ' a', ' nasa', 
'infrared-wavelength ', ' telescope', ' in', ' an', ' earth', ' satellite',
' which', ' an', ' all', ' astronomical', ' survey', ' be', ' careful', ' of',
' tricky', ' be', ' precise']

如果我使用组:r"(:?[a-z]+-[a-z]+) | (:?[a-z]+)" 两者都不是,还有另一个我认为应该的解决方案be work r[a-z]+(:?-[a-z]+)?" 也不是。

显然是可以的,但是有一点我不是很清楚。怎么了?

最佳答案

你可以使用这个:

r'[a-z]+(?:-[a-z]+)*'

关于python - 为什么我的带连字符的正则表达式不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20864110/

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