我正在使用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“an +-an+”,另一个用于简单单词r“an+”,然后我尝试使用an或r“an+-an+-”,但是输出是错误的:
[' 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']如果我使用gruops:r“(:a-z+- and +)(:?and+)”也不使用,我认为应该是工作的另一种解决方案也不使用。
这显然是可能的,但有些事情我不清楚。怎么了?
发布于 2013-12-31 23:19:20
几件事:
(?:而不是(:?如果您解决了第一个问题,则根本不需要分组。
*即字符串的空白或开始/结尾。
发布于 2013-12-31 23:21:51
你可以用这个:
r'[a-z]+(?:-[a-z]+)*'发布于 2013-12-31 23:23:43
这个大王应该能做到的。
\b[a-z]+-[a-z]+\b\b表示一个字边界.
https://stackoverflow.com/questions/20864110
复制相似问题