Currently, I am working on a small utility program in C# that aims to enhance all of my Visual Studio C# item templates by adding extra using ;
statements. To achieve this, I have developed a simple regular expression to extract the existing namespace imports in each file in order to prevent duplicates when inserting new imports.
For testing purposes, I have been using Regex101.com to validate my regular expressions before incorporating them into my C# program. However, when I implemented them in the C# program, they did not produce the expected results. This is perplexing to me, as the regex is straightforward, follows the conventions common to both .NET and ECMAScript regular expressions, and I even enabled the RegexOptions.ECMAScript
compatibility option.
const String input = @"using System;
using System.Foo;
using Foo.Bar;
namespace Foo
{
using Baz;
class Qux
{
}
}";
Regex regex = new Regex( @"^using ([\w\.]+)\;$", RegexOptions.Multiline | RegexOptions.ECMAScript );
Match match = regex.Match( input );
Assert.IsTrue( match.Success ); // The issue arises when executing this code
The discrepancy between the behavior of \w
, ^
, $
, and the multiline option in both platforms is puzzling.
Here is a screenshot depicting the successful outcome in Regex101.com:
https://i.sstatic.net/cuTVz.png
And here is a screenshot illustrating the failed attempt in .NET: