为什么我的连字号regexp不起作用?

2024-06-16 14:53:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用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]+)?“也没有。你知道吗

很明显这是可能的,但有些事情我不清楚。怎么了?你知道吗


Tags: inanisbe单词surveynasawide
3条回答

这个正则表达式应该这样做。你知道吗

\b[a-z]+-[a-z]+\b

\b表示单词边界。你知道吗

您可以使用:

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

有几件事:

  1. 你的正则表达式需要被分隔符锚定,否则你将匹配部分单词,就像现在这样
  2. 您没有对非捕获组使用正确的语法。是(?:不是(:?

如果你解决第一个问题,你根本不需要小组。你知道吗

*即字符串的空白或开头/结尾。你知道吗

相关问题 更多 >