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

标签 python regex

我正在使用 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/

相关文章:

jQuery 正则表达式选择器

java - 如何组装包含换行符并在特定字符序列处停止的正则表达式?

javascript - 正则表达式 至少使用 3 个任意字符

python - 返回具有多个键的字典中的最大值

javascript - 文本区域字符串 : limit to 1 empty line at a time

python - 在 python 中,如何检查标准输入流 (sys.stdin) 的结尾并对此做一些特殊的事情

python日志n选择k

PHP正则表达式给外部链接添加rel ="nofollow"

python - 为什么在这个 Python 正则表达式示例中会返回一个额外的结果?

PHP 相当于 Python 的 func(*[args])