find ipv4 addresses in a string using regex in javascript

Here's an example of how to find IPv4 addresses in a string using regular expressions in JavaScript:

index.tsx
const str = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed ut velit mauris. Pellentesque pretium 192.168.0.1 euismod ante a porttitor. Aenean pharetra risus at malesuada consectetur. Vestibulum congue nec 10.0.0.1 urna eget tincidunt.';

const regex = /(?:\d{1,3}\.){3}\d{1,3}/g;

const matches = str.match(regex);

console.log(matches); // Output: ["192.168.0.1", "10.0.0.1"]
392 chars
8 lines

Explanation:

  • /(?:\d{1,3}\.){3}\d{1,3}/g: This is the regular expression used to match IPv4 addresses in the given string. Let's break it down:
    • (?:\d{1,3}\.){3}: This part matches 3 occurrences of 1-3 digit numbers (\d{1,3}) followed by a dot (\.). The group is non-capturing (?: ... ) to make sure we only capture the full match (the entire IP address) and not each part separately.
    • \d{1,3}: This part matches the last part of the IPv4 address (1-3 digit number).
    • /g: This is a global flag that allows multiple matches to be found in the given string.
  • str.match(regex): This matches the regular expression against the given string and returns an array of all matches found.

gistlibby LogSnag