The problem is that ^
and $
inside character classes are not treated as anchors but as literal characters. You could simply use alternation instead of a character class:
string pattern = string.Format(@"(?:\s|^){0}(?:\s|$)",keyword);
Note that there is no need for the +
, because you just want to make sure if there is one space. You don't care if there are more of them. The ?:
is just good practice and suppresses capturing which you don't need here. And the @
makes the string a verbatim string, where you don't have to double-escape your backslashes.
There is another way, which I find slightly neater. You can use lookarounds, to ensure that there is not a non-space character to left and right of your keyword (yes, double negation, think about it). This assumption is valid if there is a space-character or if there is one end of the string:
string pattern = string.Format(@"(?<!\S){0}(?!\S)",keyword);
This does exactly the same, but might be slightly more efficient (you'd have to profile that to be certain, though - if it even matters).
You can also use the first pattern (with non-inverted logic) with (positive) lookarounds:
string pattern = string.Format(@"(?<=\s|^){0}(?=\s|$)",keyword);
However, this doesn't really make a difference to the first pattern, unless you want to find multiple matches in a string.
By the way, if your keyword
might contain regex meta-characters (like |
, $
, +
and so on), make sure to escape it first using Regex.Escape