使用正则表达式匹配不以某个字母开头的单词

Pri*_*iya 4 python regex regex-negation regex-lookarounds

我正在学习正则表达式,但无法在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']
Run Code Online (Sandbox Code Playgroud)

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

Oli*_*çon 6

与正则表达式

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

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

import re

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

print(match) # prints: ['is', 'a']
Run Code Online (Sandbox Code Playgroud)

这里查看演示。

没有正则表达式

注意,不使用正则表达式也可以实现。

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

print(match) # prints: ['is', 'a']
Run Code Online (Sandbox Code Playgroud)