CodexBloom - Programming Q&A Platform

Regex Not Matching IP Addresses with Specific Decimal Ranges in TypeScript - Need guide with Constraints

👀 Views: 252 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-11
regex typescript validation TypeScript

I'm working on a personal project and I've tried everything I can think of but I'm having a hard time understanding I'm working on a personal project and I'm trying to validate IP addresses in TypeScript using a regex pattern, but I'm working with issues when it comes to constraining the decimal ranges for the last two octets... Specifically, I want to allow only IPs where the last two octets are between 0-255 and 50-100, respectively. Here's the regex pattern I came up with: ```typescript const ipRegex = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(50|[5-9][0-9]|100)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/; ``` However, when I test it with the following IPs: - `192.168.1.50` (should match) - `10.0.0.75` (should match) - `172.16.0.150` (should NOT match) - `192.168.1.100` (should match) - `10.0.0.49` (should NOT match) - `10.0.0.101` (should NOT match) I get unexpected behaviors. For example, `10.0.0.75` matches correctly, but `172.16.0.150` also matches, which it shouldn't. It seems like my pattern is too permissive. I've tried tweaking the regex, but I keep running into either validation errors or not being strict enough. Is there a better way to structure this regex to enforce the constraints I need? Any best practices or improvements for performance would also be appreciated. I'm using TypeScript 4.5. I'm working with Typescript in a Docker container on CentOS. Thanks for any help you can provide! The project is a service built with Typescript.