Very simple regex not working

Update: As another answer pointed out, @ is not a word character so there is no word boundary between @ and space. As a workaround, you could instead use a negative lookbehind:

@"(?<!\w)@p1\b"

Original answer: You need a @ in front of your regular expressions:

@"\b@p1\b"

Without this, the string "\b" is interpreted as a backspace (character 8), not a regular expression word boundary. There is more information about @-quoted string literals on MSDN.

An alternative way without using @-quoted string literals is to escape your backslashes:

"\\b@p1\\b"

The second case is solved by @"\bINSERT\b" as stated in another answer.

However /b matches at:

  • Before the first character in the string, if the first character is a word character.
  • After the last character in the string, if the last character is a word character.
  • Between two characters in the string, where one is a word character and the other is not a word character.

A word character is one of [a-zA-Z0-9_] so the first case is not solvable by prefixing @ to escape the \b character because you are trying to then match a non word character (@).


Update: The first case can be solved by a negative look-behind assertion but also by using a negated word boundary \B which results in a more cleaner syntax (@"\B@p1\b").