使用正则表达式匹配不以特定字母开头的单词
Match words that don't start with a certain letter using regex
我正在学习正则表达式,但无法在 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']
使用正则表达式
使用否定集 [^\Wt]
匹配任何非 t 的字母数字字符。为避免匹配词的子集,请在模式开头添加词边界元字符 \b
。
此外,不要忘记您应该使用原始字符串作为正则表达式模式。
import re
text = 'this is a test'
match = re.findall(r'\b[^\Wt]\w*', text)
print(match) # prints: ['is', 'a']
查看演示 here。
没有正则表达式
请注意,无需正则表达式也可实现此目的。
text = 'this is a test'
match = [word for word in text.split() if not word.startswith('t')]
print(match) # prints: ['is', 'a']
您几乎走在了正确的轨道上。您只是忘记了 \b
(单词边界)令牌:
\b(?!t)\w+
我正在学习正则表达式,但无法在 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']
使用正则表达式
使用否定集 [^\Wt]
匹配任何非 t 的字母数字字符。为避免匹配词的子集,请在模式开头添加词边界元字符 \b
。
此外,不要忘记您应该使用原始字符串作为正则表达式模式。
import re
text = 'this is a test'
match = re.findall(r'\b[^\Wt]\w*', text)
print(match) # prints: ['is', 'a']
查看演示 here。
没有正则表达式
请注意,无需正则表达式也可实现此目的。
text = 'this is a test'
match = [word for word in text.split() if not word.startswith('t')]
print(match) # prints: ['is', 'a']
您几乎走在了正确的轨道上。您只是忘记了 \b
(单词边界)令牌:
\b(?!t)\w+