gpt4 book ai didi

python - 使用正则表达式匹配不以特定字母开头的单词

转载 作者:太空宇宙 更新时间:2023-11-03 13:28:59 24 4
gpt4 key购买 nike

我正在学习正则表达式,但无法在 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']

关于python - 使用正则表达式匹配不以特定字母开头的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50374496/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com