© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•4y ago•
3 replies
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
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?
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

Minor Error Handling ; TryGetValue returning null [Answered]
C#CC# / help
4y ago
multiple capture groups regex [Answered]
C#CC# / help
4y ago
❔ Convert regex match groups into parameters
C#CC# / help
3y ago