【问题标题】:Match words that don't start with a certain letter using regex使用正则表达式匹配不以某个字母开头的单词
【发布时间】:2018-10-26 17:18:57
【问题描述】:

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

【问题讨论】:

标签: python regex regex-negation regex-lookarounds


【解决方案1】:

使用正则表达式

使用否定集[^\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']

【讨论】:

    【解决方案2】:

    你几乎是在正确的轨道上。你只是忘记了\b(字边界)令牌:

    \b(?!t)\w+
    

    Live demo

    【讨论】:

    • 谢谢。实际上 match=re.findall(r'\b(?!t)\w+',text) 工作。它正在寻找原始字符串
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-25
    • 1970-01-01
    • 2013-11-23
    • 1970-01-01
    相关资源
    最近更新 更多