Skip to main content
 首页 » 编程设计

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

2025年05月04日26zlslch

我正在使用 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]+)*'