Home > Blockchain >  Need help in Regex to extract domains using Regex
Need help in Regex to extract domains using Regex

Time:06-22

Can anyone help to write a regex to extract domains like below:

If values are:

dns.google
x2.xdn.cbn.com
hello.1234.extra.net.com

then my regex should give output to me as below:

  • dns.google --- no match
  • x2.xdn.cbn.com --- extracts cbn.com only
  • hello.1234.extra.net.com ---extracts net.com only.

I tried with negative lookbehind but failed.

Example: (?<=\.).

CodePudding user response:

Assuming that you have your input in a file called domains.txt and you would like to match the last two parts of each domain which has more than two parts, a grep-based solution could look like this:

grep -Po "[.]\K[^.] [.][^.] $" domains.txt
  • Related