首页 > 解决方案 > 使用正则表达式匹配不以某个字母开头的单词

问题描述

我正在学习正则表达式,但无法在 python 中找到正确的正则表达式来选择以特定字母开头的字符。

下面的例子

text='this is a test'
match=re.findall('(?!t)\w*',text)

# match returns
['his', '', 'is', '', 'a', '', 'est', '']

match=re.findall('[^t]\w+',text)

# match
['his', ' is', ' a', ' test']

预期的 :['is','a']

标签: pythonregexregex-negationregex-lookarounds

解决方案


使用正则表达式

使用否定集[^\Wt]匹配任何不是t的字母数字字符。\b为避免匹配单词子集,请在模式的开头添加单词边界元字符 , 。

此外,不要忘记您应该将原始字符串用于正则表达式模式。

import re

text = 'this is a test'
match = re.findall(r'\b[^\Wt]\w*', text)

print(match) # prints: ['is', 'a']

在此处查看演示。

没有正则表达式

请注意,这也可以在没有正则表达式的情况下实现。

text = 'this is a test'
match = [word for word in text.split() if not word.startswith('t')]

print(match) # prints: ['is', 'a']

推荐阅读