2016-02-29 26 views
1

我希望将一个句子分割为非单词字符(不包括短划线,可能表示连字符)的单词列表和连续的破折号。我的意思是:“旋转木马”是一个字,而不是三个字; “条件 - 但”是两个字:删除连续的破折号。python正则表达式 - 分割为非单词字符或连续短划线,但不是单短划线

我尝试以下和它不工作: listofwords = [word for word in re.split('[^a-zA-Z0-9]|-{2,}',sentence)]

我可以提供一个样品的句子: sentence = 'sample sentence---such as well-being {\t' 和期望的结果是[“样本”,“句子”,“例如”,“如','福祉']。

+0

[regex101.com](http://regex101.com)是一个很好的正则表达式测试工具 – Martin

+0

可以在这个' - {2,} | \ s'上分割。 – lintmouse

+0

你可以做两遍:首先,用空格替换--- ---,然后正常分割。 –

回答

2

你可以使用这个表达式:

\w+(?:-\w+)* 

RegEx Demo

代码:

p = re.compile(r'\w+(?:-\w+)*') 
test_str = "sample sentence---such as well-being { " 

re.findall(p, test_str) 

输出:

['sample', 'sentence', 'such', 'as', 'well-being'] 
+2

**▲**正确,快速。 – 2016-02-29 21:10:21

相关问题