find ipv4 addresses in a string using regex in typescript

To find IPv4 addresses in a string using regex in Typescript, you can use the following regular expression:

index.ts
const text: string = "Lorem ipsum dolor sit amet, 192.168.0.1 consectetur adipiscing elit. Sed auctor 10.0.0.1 sagittis turpis, sed consequat ligula consequat vitae. Sed odio nulla, luctus sed velit vel";
const regex: RegExp = /\b(?:\d{1,3}\.){3}\d{1,3}\b/g;
const ipv4Addresses: RegExpMatchArray | null = text.match(regex);
console.log(ipv4Addresses); // Output: ["192.168.0.1", "10.0.0.1"]
392 chars
5 lines

Explanation:

  • \b: Matches a word boundary, ensuring that the regex only matches within words.
  • (?:\d{1,3}\.){3}: Matches three occurrences of one to three digits followed by a period, capturing them as a non-capturing group using (?:...).
  • \d{1,3}: Matches one to three digits.
  • \b: Matches a word boundary, ensuring that the regex only matches within words.
  • g: Enables global matching, allowing the regex to match multiple occurrences within the string.

The text.match(regex) method returns an array of all matches found in the string, which can then be used as needed.

gistlibby LogSnag