Skip to content
Advertisement

Regex to return all subdomains from a given domain

Given a domain string like aaaa.bbbb.cccc.dddd I am trying to iterate over all of its subdomains i.e.

JavaScript

I thought this regex ((?:[a-zA-Z0-9]+.)*)([a-zA-Z0-9]+)$ should do the trick (please ignore the fact, that I am only matching these characters [a-zA-Z0-9]), however it only matches the full string.

How can I modify it to make it work?

Edit 1: The following code

JavaScript

should print (in any order)

JavaScript

Advertisement

Answer

The regex you’re looking for is

JavaScript

This pattern is based on lookahead. It can cross-match substrings that have already been matched in previous iterations.

Java Example

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement