Do regular expressions from the re module support word boundaries (\b)?

前端 未结 4 795
闹比i
闹比i 2020-11-22 03:38

While trying to learn a little more about regular expressions, a tutorial suggested that you can use the \\b to match a word boundary. However, the following sn

4条回答
  •  执念已碎
    2020-11-22 04:14

    Why don't you try

    word = 'two'
    re.compile(r'\b%s\b' % word, re.I)
    

    Output:

    >>> word = 'two'
    >>> k = re.compile(r'\b%s\b' % word, re.I)
    >>> x = 'one two three'
    >>> y = k.search( x)
    >>> y
    <_sre.SRE_Match object at 0x100418850>
    

    Also forgot to mention, you should be using raw strings in your code

    >>> x = 'one two three'
    >>> y = re.search(r"\btwo\b", x)
    >>> y
    <_sre.SRE_Match object at 0x100418a58>
    >>> 
    

提交回复
热议问题