Regular expression: Replace everything before first occurence

Viewed 55

I have the following regular expression that I'm using to remove the dev. part of my URL.

String domain = "dev.mydomain.com";
System.out.println(domain.replaceAll(".*\\.(?=.*\\.)", ""));

Outputs: mydomain.com but this is giving me issues when the domains are in the vein of dev.mydomain.com.pe or dev.mydomain.com.uk in those cases I am getting only the .com.pe and .com.uk parts.

Is there a modifier I can use on my regex to make sure it only takes what is before the first . (dot included)?

Desired output:

dev.mydomain.com -> mydomain.com

stage.mydomain.com.pe -> mydomain.com.pe

test.mydomain.com.uk -> mydomain.com.uk

2 Answers

You may use

^[^.]+\.(?=.*\.)

See the regex demo and the regex graph:

enter image description here

Details

  • ^ - start of string
  • [^.]+ - 1 or more chars other than dots
  • \. - a dot
  • (?=.*\.) - followed with any 0 or more chars other than line break chars as many as possible and then a ..

Java usage example:

String result = domain.replaceFirst("^[^.]+\\.(?=.*\\.)", "");

Following regex will work for you. It will find first part (if exists), captures rest of the string as 2nd matching group and replaces the string with 2nd matching group. .*? is non-greedy search that will match until it sees first dot character.

(.*?\.)?(.*\..*)

Regex Demo

sample code:

String domain = "dev.mydomain.com";
System.out.println(domain.replaceAll("(.*?\\.)?(.*\\..*)", "$2"));

domain = "stage.mydomain.com.pe";
System.out.println(domain.replaceAll("(.*?\\.)?(.*\\..*)", "$2"));

domain = "test.mydomain.com.uk";
System.out.println(domain.replaceAll("(.*?\\.)?(.*\\..*)", "$2"));

domain = "mydomain.com";
System.out.println(domain.replaceAll("(.*?\\.)?(.*\\..*)", "$2"));

output:

mydomain.com
mydomain.com.pe
mydomain.com.uk
mydomain.com
Related