我正在使用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]+”的正则表达式,然后我尝试了一个或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']
如果我使用groops:r“(:?[a-z]+-[a-z]+)|(:?[a-z]+)“两者都不是,我认为另一个解决方案应该是workr”[a-z]+(:?-[a-z]+)?“也没有。你知道吗
很明显这是可能的,但有些事情我不清楚。怎么了?你知道吗
这个正则表达式应该这样做。你知道吗
\b
表示单词边界。你知道吗您可以使用:
有几件事:
(?:
不是(:?
如果你解决第一个问题,你根本不需要小组。你知道吗
*即字符串的空白或开头/结尾。你知道吗
相关问题 更多 >
编程相关推荐