0

I want to remove the domain information from hostnames. E.g. I want "server1.mydomain.com" to be just "server1". I thought I had it with:

^(\w*)

But then I realized I also have hostnames like "desktop-1.mydomain.com", and they all got changed to "desktop" and not "desktop-1" etc. Any suggestions how to do this?

HugoTeixeira
  • 4,674
  • 3
  • 22
  • 32
kodax
  • 3
  • 1
  • 1
    Try `^[^.]+` to match up to the first dot. – Wiktor Stribiżew Oct 09 '18 at 17:55
  • Excellent! And really fast answer! Thanks a lot, fantastic first experience at this site:) I do not understand how I can mark this as the solution, though. – kodax Oct 09 '18 at 18:16
  • @kodax There is a check on the left side of the answer (under the number of votes). You can click on it in order to mark it as the accepted solution. – HugoTeixeira Oct 09 '18 at 18:27

1 Answers1

1

As already mentioned by Wiktor in the comments, the easiest regular expression is

^[^.]+

The explanation from regex101.com is:

^ asserts position at start of a line
Match a single character not present in the list below [^.]+
+ Quantifier — Matches between one and unlimited times, as many times as 
possible, giving back as needed (greedy)
. matches the character . literally (case sensitive)

If you are using a programming language, another possible solution is to split the string in the dot character and get the first element of the resulting array. For example:

const array1 = 'server1.mydomain.com'.split(/\./);
console.log(array1[0]);

const array2 = 'desktop-1.mydomain.com'.split(/\./);
console.log(array2[0]);

Prints:

server1
desktop-1
HugoTeixeira
  • 4,674
  • 3
  • 22
  • 32