python - 使用正则表达式匹配不以某个字母开头的单词
问题描述
我正在学习正则表达式,但无法在 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']
推荐阅读
- javascript - How do I apply the same .onclick function to multiple elements?
- ionic-framework - Ionic Virtual Scroll 是否有问题?
- excel - Function that finds maximum value in the selected cells
- r - 读取excel文件时列中的值发生变化
- docker - 使用 .NetCore 的 Docker,我应该使用 SDK 还是运行时映像进行微服务?
- python - 这不是与装饰者的工作方式相反吗?
- html - Create fixed element that has different background color on different background elements?
- sql - 计算具有特定值的记录数并映射到不同的表
- google-apps-script - 如何从脚本中排除某些工作表?
- python - 如何使用 .apply 和用户定义的函数在 pandas df 中创建列