C
C#2y ago
Kiel

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 and 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 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?
2 Replies
HimmDawg
HimmDawg2y ago
If you use d20 as your input, you'll end up getting an empty string als the value for the "count" group The group will always be captured (even though it doesn't have a value) thus you get true for the trygetvalue and the code will try to parse this empty string
Kiel
Kiel2y ago
oh, I assumed (since I was using regex101 to test) that if there was no input, there would be no group at all