捕获单词中至少一个标点字符的正则表达式
我想找出所有包含至少一个标点符号(或者任何不是空格、也不是字母数字的字符)的单词,这个标点符号可以出现在单词的开头、中间或者结尾。比如,在这句话中
this is a wo!rd right !and| other| hello |other
这个正则表达式会返回
wo!rd !and| other| |other
1 个回答
8
你可以使用这个:
>>> sentence = "this is a wo!rd right !and| other| hello |other"
>>> import re
>>> re.findall("\S*[^\w\s]\S*", sentence)
['wo!rd', '!and|', 'other|', '|other']
这个可以找到所有包含至少一个非字母、非空格
字符的单词。\S
和[^\s]
是一样的。
正则表达式解释:
\S* # Match 0 or more non-space character
[^\w\s] # Match 1 non-space non-word character
\S* # Match 0 or more non-space character