Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

netstandard - Regular Expression, Group Name inaccessible

In .NET Core and .NET Framework 4.x the following code works as expected:

var match = Regex.Match(src, pattern)
    .Groups
    .Cast<Group>()
    .Where(grp => grp.Name.StartsWith("val"));

However, in netstandard, the Name property in Group is gone. I'm wondering if there is a new way of achieving the same thing, or if this is a bug.


Edit: I first thought this was a netstandard 2.0 issue, but it looks like the property is missing from all netstandard versions.

Workaround for now: .Where(grp => ((string)((dynamic)grp).Name).StartsWith("val")), which is obviously less than ideal.

like image 236
Andre Andersen Avatar asked Jul 03 '17 00:07

Andre Andersen


2 Answers

According to its entry on apisof.net this property is only available on .NET Core 1.1 and .NET Framework 4.7 and upwards and has not been added to any version of .NET Standard. On other platforms (lower .NET versions, Xamarin, …) your workaround might throw an exception at runtime.

If you absolutely need to use this property in a library, I suggest multi-targeting to net47;netcoreapp1.1 instead of targeting a version of .NET Standard.

You are seeing the property in the debugger even if you target 4.5 because you are actually running on .NET 4.7 (because it is the version you have installed) and the debugger will show you everything that is available at runtime. The compiler however limits you the minimum version of .NET (Framework/Standard/…) you are targeting.

like image 50
Martin Ullrich Avatar answered Oct 24 '22 11:10

Martin Ullrich


Named groups could be accessed through Regex.GetGroupNames(), it works on .NET Standard either.

Useful sample found at Regex.GetGroupNames Method

like image 20
AhmadYo Avatar answered Oct 24 '22 12:10

AhmadYo