繁体   English   中英

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

[英]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']

请在此处查看演示。

没有正则表达式

请注意,如果没有正则表达式,这也是可以实现的。

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+

现场演示

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM