Kumar Vaibhav
Kumar Vaibhav

Reputation: 2642

C# Regular Expression matching but not Regexr.com

Maybe I am doing something wrong here but it seems weird to me that when I try to match the string "radiologic examination eye detect foreign body" against the regular expression "\b*ct\b" on regexr.com then I find no match but when I try and do the same thing using a C# program, it matches. C# code is given below. Am I doing/checking something wrong?

string desc = "radiologic examination eye detect foreign body";
string regex = "\\b" + "*ct" + "\\b";
if (Regex.IsMatch(desc, regex))
{
    String x = Regex.Replace(desc, regex, " " + "ct" + " ").Trim();
    Console.WriteLine(x);
}

Thanks in advance!

Upvotes: 5

Views: 898

Answers (2)

Mathew Thompson
Mathew Thompson

Reputation: 56429

It's matching because you've got an asterisk in there.

An asterisk means:

Matches the preceding character zero or more times

So it's not matching the \b at all, but still satisfying the above condition.

Remove this and it no longer matches:

string regex = "\\b" + "ct" + "\\b";

Upvotes: 3

Guvante
Guvante

Reputation: 19203

C# is probably interpreting \b* as 0 or more word boundaries.

Since this is an odd definition, maybe regexr is disallowing the contruct and treating it as \b. For instance this could be the case if it is using a different regex backend and a translation to C#.

Are you sure you didn't mean \b.*ct\b which would be a word boundary followed by any number of characters followed by ct and another word boundary?

Upvotes: 1

Related Questions