A Comprehensive Guide to ip-regex for Efficient IP Address Validation and Extraction

Introduction to ip-regex

ip-regex is a powerful JavaScript library designed to help developers validate and extract IP addresses from strings with ease. This library supports both IPv4 and IPv6 formats, ensuring comprehensive IP address management in your applications. This guide will delve into various API functionalities provided by ip-regex and how you can leverage these APIs in your applications.

Installation

npm install ip-regex

API Examples

1. Basic IP Address Matching

To match an IP address in a string:


  const ipRegex = require('ip-regex');

  const string = 'The server is reachable at 192.168.0.1';
  const result = string.match(ipRegex());

  console.log(result); // ['192.168.0.1']

2. Validating an IP Address

Check if a string is a valid IP address:


  const ipRegex = require('ip-regex');

  const ip = '192.168.0.1';
  const isValid = ipRegex({ exact: true }).test(ip);

  console.log(isValid); // true

3. Matching All IP Addresses in a String

Extract all IP addresses from a given string:


  const ipRegex = require('ip-regex');

  const text = 'Server1: 192.168.0.1, Server2: 10.0.0.2';
  const ips = text.match(ipRegex());

  console.log(ips); // ['192.168.0.1', '10.0.0.2']

4. Supporting IPv6

Match both IPv4 and IPv6 addresses:


  const ipRegex = require('ip-regex');

  const text = 'IPv4: 192.168.0.1 and IPv6: fe80::1';
  const ips = text.match(ipRegex({ includeBoundaries: true }));

  console.log(ips); // ['192.168.0.1', 'fe80::1']

5. Find IP Addresses in Text Using Boundaries

Use boundaries to reduce false positives when matching IP addresses within text:


  const ipRegex = require('ip-regex');

  const text = 'Meet me at 10.10.10.10';
  const ips = text.match(ipRegex({ includeBoundaries: true }));

  console.log(ips); // ['10.10.10.10']

Application Example

Here is a simple Node.js application to extract and validate IP addresses from user input:


  const readline = require('readline');
  const ipRegex = require('ip-regex');

  const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
  });

  rl.question('Enter a string to extract IP addresses: ', (answer) => {
    const ips = answer.match(ipRegex({includeBoundaries: true}));
    if (ips) {
      console.log('Extracted IP addresses:', ips);
    } else {
      console.log('No IP addresses found.');
    }
  });

Using the above code, execute the file using node command and provide a string containing IP addresses. The application will extract and display all the IP addresses present in that string.

For more detailed documentation, please visit the official repository on GitHub.

Hash: dd2da0292adc0c359c1db31f490867f1363a473ed6d91f28291d123d18bc8bdb

Leave a Reply

Your email address will not be published. Required fields are marked *