2

Example:

def searchResult(expr, inputStr):
    if (re.search(expr, inputStr)):
        return True
    return False

print(searchResult("\s", "the quick brown fox")) # True
print(searchResult("\bfox", "the quick brown fox")) # False
print(searchResult("\\bfox", "the quick brown fox")) # True

I need double backslash "\\b" for word boundaries, but just single backslash "\s" is acceptable for whitespace characters. Why is the double backslash required for word boundaries?

martineau
  • 119,623
  • 25
  • 170
  • 301
sdMarth
  • 521
  • 1
  • 8
  • 15
  • 2
    See [Backslashes in Python Regular Expressions](https://stackoverflow.com/questions/33582162/backslashes-in-python-regular-expressions), too. – Wiktor Stribiżew May 23 '18 at 20:35

1 Answers1

11

\b has a special meaning: it's the backspace character. \s and many other \<something> sequences have no special meaning so \ is then interpreted as a literal slash.

>>> '\b'
'\x08'
>>> print('123\b456')
12456
>>> '\s'
'\\s'
>>> print('\s')
\s
>>> print('\b')

>>> # nothing visible printed above

To make things easier, you should usually use raw string literals when writing regexes. This generally prevents \ from being interpreted as an escape character in the Python string sense, so that it works properly in your regex. For example:

>>> r'\b'
'\\b'
>>> print(r'\b')
\b
Alex Hall
  • 34,833
  • 5
  • 57
  • 89