Skip to main content
 首页 » 编程设计

python 正则表达式——按非单词字符或连续破折号拆分,但不按单个破折号拆分

2024年08月23日26mayingbao

我希望将一个句子拆分为非单词字符(不包括破折号,可能表示连字符)和连续破折号的单词列表。我的意思是:“旋转木马”是一个字,不是三个字; “条件--但是”是两个词:去掉连续的破折号。

我尝试了以下方法,但它不起作用: listofwords = [re.split('[^a-zA-Z0-9]|-{2,}',sentence)]

中的单词

我可以提供一个例句: sentence = '例句---如幸福{\t' 期望的结果是 ['sample', 'sentence', 'such', 'as', 'well-being']。

请您参考如下方法:

你可以使用这个正则表达式:

\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']