Search code examples
objective-cregexword-boundary

\b vs \\b in regex


As I see in regex documentation that \b match word boundary. I prepare a string

"db bd how to"

and regex

\b(a|b)(c|d)\b

I think when running the regex, it should match "bd" in the string, but it don't.

But if the regex is

\\b(a|b)(c|d)\\b

it matches.

Can you explain the difference?


Solution

  • There are several layers of escaping at work here

    regex -----------------> | regex literal -> | string literal
    -------------------------+------------------+---------------
    word boundary            | \b               | \\b
    alternation ("a" or "b") | (a|b)            | (a|b)
    alternation ("c" or "d") | (c|d)            | (c|d)
    word boundary            | \b               | \\b