CodexBloom - Programming Q&A Platform

Regex scenarios to Match Specific IP Address Format in Node.js - implementing Leading Zeros

👀 Views: 405 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-23
regex node.js validation JavaScript

I'm trying to validate IP addresses in a Node.js application using regex, but I'm running into issues with leading zeros. My intention is to match valid IPv4 addresses while ensuring that numbers like '192.168.01.10' are not considered valid due to the leading zero. Here's the regex I've been using: ```javascript 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]?)\.(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]?)$/; const testIp = '192.168.01.10'; console.log(ipRegex.test(testIp)); // Expected: false, Actual: true ``` What I expected was for the regex to return `false` for IP addresses that contain leading zeros in any octet. However, it is matching the above IP address as valid. I tried modifying the regex to exclude leading zeros like this: ```javascript const ipRegexLeadingZeros = /^(25[0-5]|2[0-4][0-9]|[1-9][0-9]?|[0-9])\.(25[0-5]|2[0-4][0-9]|[1-9][0-9]?|[0-9])\.(25[0-5]|2[0-4][0-9]|[1-9][0-9]?|[0-9])\.(25[0-5]|2[0-4][0-9]|[1-9][0-9]?|[0-9])$/; console.log(ipRegexLeadingZeros.test(testIp)); // Expected: false, Actual: true ``` The current pattern is still allowing `192.168.01.10` to be considered valid. How can I properly enforce the rule against leading zeros while still matching valid IP addresses? Any insights would be appreciated! What's the best practice here?