Python regular expression match whole word

后端 未结 4 1062
梦毁少年i
梦毁少年i 2020-11-21 06:05

I\'m having trouble finding the correct regular expression for the scenario below:

Lets say:

a = \"this is a sample\"

I want to mat

4条回答
  •  无人共我
    2020-11-21 06:33

    Try using the "word boundary" character class in the regex module, re:

    x="this is a sample"
    y="this isis a sample."
    regex=re.compile(r"\bis\b")  # For ignore case: re.compile(r"\bis\b", re.IGNORECASE)
    
    regex.findall(y)
    []
    
    regex.findall(x)
    ['is']
    

    From the documentation of re.search().

    \b matches the empty string, but only at the beginning or end of a word

    ...

    For example r'\bfoo\b' matches 'foo', 'foo.', '(foo)', 'bar foo baz' but not 'foobar' or 'foo3'

提交回复
热议问题