首页 > 解决方案 > 正则表达式 '[\w-]+(\.[\w-]+)*' 不匹配

问题描述

我想处理PostgreSQL文档中的一些句子并做一些分析。在分词阶段,我尝试使用Lotufo 等人提出的正则表达式'[\w-]+(.[\w-]+)*' 。在文章Modeling the Hurried bug report 阅读过程中总结了 bug 报告。很奇怪,我在 Python 中使用这个正则表达式无法得到预期的答案。

Python 3.6.5 |Anaconda, Inc.| (default, Mar 29 2018, 13:32:41) [MSC v.1900 64 bit (AMD64)]
Type "copyright", "credits" or "license" for more information.

IPython 6.4.0 -- An enhanced Interactive Python.
>>> import re
>>> result = re.findall(r'[\w-]+(\.[\w-]+)*', 'Specifies the directory to use for data storage.')
>>> print(result)

我期望得到一个单词列表:</p>

['Specifies', 'the', 'directory', 'to', 'use', 'for', 'data', 'storage']

但我只有一个空字符串列表:

['', '', '', '', '', '', '', '']

有谁知道我的代码有什么问题?非常感谢。

标签: regexpython-3.x

解决方案


这按您期望的方式工作:

Python 3.7.2 (default, Jan 16 2019, 19:49:22) 
[GCC 8.2.1 20181215 (Red Hat 8.2.1-6)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import re
>>> split = re.compile('(\w+)')
>>> split.findall('Specifies the directory to use for data storage.')
['Specifies', 'the', 'directory', 'to', 'use', 'for', 'data', 'storage']
>>> 

正则表达式上的那些方括号感觉不对。我想他们是原因。


推荐阅读