LukeHennerley
LukeHennerley

Reputation: 6444

Regular expression with word boundaries is not matching

I am trying to compute a regular expression to use with TFS Power Tools with the DocumentWell feature.

I am testing this in a console application at the moment.

Console.WriteLine(Regex.IsMatch(@"C:\User\User\My Documents\Visual Studio 2010\Project\", "\bProject\b"));

This is what I have tried (output is "False", so my regex string is \bProject\b. I have followed through the following link:

http://www.regular-expressions.info/wordboundaries.html

Which I thought that I understood... I really struggle with regex so could somebody help me out with this regex and explain what I am doing wrong?

Upvotes: 0

Views: 118

Answers (1)

stema
stema

Reputation: 93046

Use also a verbatim string for the regex, see String literals on msdn

Console.WriteLine(Regex.IsMatch(@"C:\User\User\My Documents\Visual Studio 2010\Project\", @"\bProject\b"));

otherwise you have to escape twice

Console.WriteLine(Regex.IsMatch(@"C:\User\User\My Documents\Visual Studio 2010\Project\", "\\bProject\\b"));

See the difference of regular and verbatim string

string input = @"C:\User\User\My Documents\Visual Studio 2010\Project\";

string reg = "\bProject\b";
string regVerbatim = @"\bProject\b";

Regex r = new Regex(reg);
Regex rVerbatim = new Regex(regVerbatim);

Console.Write("Regular String regex: " + r.ToString() + " isMatch :");
Console.WriteLine(r.IsMatch(input));
Console.Write("Verbatim String regex: " + rVerbatim.ToString() + " isMatch :");
Console.WriteLine(rVerbatim.IsMatch(input));

Output:

Regular String regex:Projec isMatch :False
Verbatim String regex: \bProject\b isMatch :True

In the regular string the last "t" of the Regex is deleted and also the empty string before the word, that is because the string interpreted \b as backspace and doesn't hand it over to the regex interpreter.

So either escape the backslash so that from \\bProject\\b \bProject\b is handed to the regex interpreter, or use a verbatim string, so that the string doesn't interprets the \b.

Upvotes: 2

Related Questions