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

前端 未结 4 617
闹比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 03:59

    Just to explicitly explain why re.search("\btwo\b", x) doesn't work, it's because \b in a Python string is shorthand for a backspace character.

    print("foo\bbar")
    fobar
    

    So the pattern "\btwo\b" is looking for a backspace, followed by two, followed by another backspace, which the string you're searching in (x = 'one two three') doesn't have.

    To allow re.search (or compile) to interpret the sequence \b as a word boundary, either escape the backslashes ("\\btwo\\b") or use a raw string to create your pattern (r"\btwo\b").

提交回复
热议问题