正则表达式:如何删除FQN

时间:2018-10-09 17:54:35

标签: regex

我想从主机名中删除域信息。 例如。我希望"server1.mydomain.com"只是"server1"。 我以为我拥有它:

^(\w*)

但是后来我意识到我也有"desktop-1.mydomain.com"这样的主机名,它们都被更改为"desktop"而不是"desktop-1"等。 有什么建议怎么做吗?

1 个答案:

答案 0 :(得分:1)

正如Wiktor在评论中所提到的,最简单的正则表达式是

^[^.]+

regex101.com的解释是:

^ 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)

如果使用的是编程语言,另一种可能的解决方案是将字符串拆分为点字符并获取结果数组的第一个元素。例如:

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

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

打印:

server1
desktop-1