empty regex groups returning true from TryGetValue??
I have the following regex:
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:
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
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 stringoh, I assumed (since I was using regex101 to test) that if there was no input, there would be no group at all