empty regex groups returning true from TryGetValue??
I have the following regex:
(?<count>[\d])?d(?<sides>[\d]+)
(?<count>[\d])?d(?<sides>[\d]+)
Which allows a diceroll to omit the count (number) of dice rolled with a default of 1. So both
1d20
1d20
and
d20
d20
are meant to be valid. However, through some testing, C# regex seems to think the "count" group is populated even though it isn't. The following (arguably bad) code throws FormatException if, for example,
d20
d20
is the input:
var count = match.Groups.TryGetValue("count", out var group) ? Math.Max(int.Parse(group.Value), 1) : 1;
var count = match.Groups.TryGetValue("count", out var group) ? Math.Max(int.Parse(group.Value), 1) : 1;
I opted not to use int.TryParse because I assumed the regex group would pick up the valid digits, or TryGetValue would return false, but apparently neither is happening. What gives?