python regex to detect a word exists

前端 未结 3 1863
庸人自扰
庸人自扰 2020-12-18 11:04

I want to detect whether a word is in a sentence using python regex. Also, want to be able to negate it.

import re
re.match(r\'(?=.*\\bfoo\\b)\', \'bar red f         


        
3条回答
  •  余生分开走
    2020-12-18 11:50

    To detect if a word exists in a string you need a positive lookahead:

    (?=.*\bfoo\b)
    

    The .* is necessary to enable searching farther than just at the string start (re.match anchors the search at the string start).

    To check if a string has no word in it, use a negative lookahead:

    (?!.*\bbar\b)
     ^^^
    

    So, combining them:

    re.match(r'(?=.*\bfoo\b)(?!.*\bbar\b)', input)
    

    will find a match in a string that contains a whole word foo and does not contain a whole word bar.

提交回复
热议问题