首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么我对连字符的正则表达式不起作用?

为什么我对连字符的正则表达式不起作用?
EN

Stack Overflow用户
提问于 2013-12-31 23:13:25
回答 3查看 104关注 0票数 1

我正在使用python的re模块编写一个正则表达式,以便与简单单词和单个连字符匹配,例如:

代码语言:javascript
复制
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."""

应匹配:

代码语言:javascript
复制
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+-”,但是输出是错误的:

代码语言:javascript
复制
[' 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+)”也不使用,我认为应该是工作的另一种解决方案也不使用。

这显然是可能的,但有些事情我不清楚。怎么了?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2013-12-31 23:19:20

几件事:

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

如果您解决了第一个问题,则根本不需要分组。

*即字符串的空白或开始/结尾。

票数 2
EN

Stack Overflow用户

发布于 2013-12-31 23:21:51

你可以用这个:

代码语言:javascript
复制
r'[a-z]+(?:-[a-z]+)*'
票数 3
EN

Stack Overflow用户

发布于 2013-12-31 23:23:43

这个大王应该能做到的。

代码语言:javascript
复制
\b[a-z]+-[a-z]+\b

\b表示一个字边界.

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20864110

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档