CodexBloom - Programming Q&A Platform

Regex Not Matching Numeric Ranges in C# - implementing Inclusive and Exclusive Boundaries

πŸ‘€ Views: 34 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-26
regex c# .net C#

I'm refactoring my project and I'm reviewing some code and I'm trying to debug I'm relatively new to this, so bear with me... I'm trying to validate numeric ranges in a string format like "5-10", but I want to include the boundaries in the matches for some cases. My requirement is to capture instances where the range can either be inclusive (both numbers are part of the range) or exclusive (only numbers outside the range are valid) depending on the context. I've written a regex pattern that I thought would capture this, but it doesn't seem to work as expected. Here’s what I have so far: ```csharp string pattern = "^(\d+)-(\d+)$"; Regex regex = new Regex(pattern); ``` When I run this against the string "5-10", I get a successful match. However, I also need to account for cases like "(5-10)" for exclusive ranges, which doesn't match with my current pattern. I tried modifying the regex to include optional parentheses, but I'm working with issues with back-references and capturing groups. Here's my revised attempt: ```csharp string pattern = "^\(?\d+-\d+\)?$"; ``` Now, it matches both "5-10" and "(5-10)", but it loses the individual number captures, and I need to tell if they're inclusive or exclusive without additional logic. I need to capture both numbers as separate groups regardless of parentheses and determine how to treat the boundaries based on whether they are included or not. I've also looked into using named capturing groups, but I’m not quite sure how to implement that in this context. For example, if the input is "(5-10)", I would like to extract both numbers and know that they are exclusive. Additionally, I'm using .NET 5.0 and I would appreciate any advice on best practices for handling such regex patterns efficiently. Any help would be greatly appreciated! Is there a better approach? My team is using C# for this application. Thanks for taking the time to read this!