If you want to match a c++
between non-word chars (chars other than letters, digits and underscores) you may use
\bc\+\+\B
See the regex demo where \b
is a word boundary and \B
matches all positions that are not word boundary positions.
C# syntax:
var pattern = @"\bc\+\+\B";
You must remember that \b
/ \B
are context dependent: \b
matches between the start/end of string and the adjoining word char or between a word and a non-word chars, while \B
matches between the start/end of string and the adjoining non-word char or between two word or two non-word chars.
If you build the pattern dynamically, it is hard to rely on word boundary \b
pattern.
Use adaptive dynamic wod boundaries, (?!\B\w)
and (?<!\w\B)
lookarounds instead, they will always match a word not immediately preceded/followed with a word char if the word starts/ends with a word char:
var pattern = $@"(?!\B\w){Regex.Escape(word)}(?<!\w\B)";
If the word boundaries you want to match are whitespace boundaries (i.e. the match is expected only between whitespaces), use
var pattern = $@"(?<!\S){Regex.Escape(word)}(?!\S)";