Question 50

Question

Can you explain how to create a regular expression that matches a valid IP address?

Answer

Here's a breakdown of creating a regular expression (regex) for validating IP addresses in JavaScript, along with explanations and considerations:

Regular Expression:

const ipRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;

Explanation:

  • ^ and $: Match the beginning and end of the string, ensuring the entire input is an IP address.

  • (?:...): Non-capturing groups – used to group parts of the regex without creating separate capture groups. This keeps things clean and readable.

  • (?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.: Matches a single byte of an IP address (0-255):

    • 25[0-5]: Matches 250 to 255.

    • 2[0-4][0-9]: Matches 200 to 249.

    • [01]?[0-9][0-9]?: Matches 0 to 199, allowing for optional leading "0" or "1".

    • \.: Matches a literal period (.), separating the bytes.

  • {3}: Repeats the preceding group (a byte and period) three times, ensuring there are four bytes in total.

  • (?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$: Matches the final byte of the IP address, using the same pattern as before.

Usage Example:

const ipAddress = "192.168.1.1";

if (ipRegex.test(ipAddress)) {
  console.log("Valid IP address");
} else {
  console.log("Invalid IP address");
}

Important Notes:

  • This regex only validates the format of an IP address. It doesn't check if the address is actually reachable or assigned to a device.

  • For more complex validation needs (e.g., IPv6, network ranges), you might need a more sophisticated regex or consider using a dedicated library.

Last updated