如何从FQDN中提取shortName?Java/Scala实现方案求助
从FQDN提取ShortName的实现思路
步骤1:明确匹配规则
观察示例可总结核心规则:需要移除FQDN末尾的固定后缀,目前已知两类目标后缀:
domain.netdom-as-me.domain.net
匹配逻辑:优先匹配更长的后缀(dom-as-me.domain.net),匹配成功则移除该部分;否则匹配较短后缀(domain.net)并移除,剩余部分即为ShortName。
步骤2:Java实现方案
方式1:字符串后缀匹配
直接通过endsWith检查后缀,截取保留部分:
public class FQDNProcessor { private static final String[] SUFFIXES = {"dom-as-me.domain.net", "domain.net"}; public static String extractShortName(String fqdn) { for (String suffix : SUFFIXES) { if (fqdn.endsWith(suffix)) { // 减去后缀长度和前面的分隔点 return fqdn.substring(0, fqdn.length() - suffix.length() - 1); } } // 无匹配后缀时返回原字符串,可根据需求调整 return fqdn; } public static void main(String[] args) { String[] testCases = { "node.a.domain.net", "node.a.dev.domain.net", "node.a.sbx.domain.net", "node.a.b.domain.net", "node.a.dev.dom-as-me.domain.net", "node.a.dom-as-me.domain.net" }; for (String fqdn : testCases) { System.out.printf("%s => %s%n", fqdn, extractShortName(fqdn)); } } }
方式2:正则表达式匹配
用正则捕获后缀前的目标内容:
import java.util.regex.Matcher; import java.util.regex.Pattern; public class FQDNRegexProcessor { private static final Pattern FQDN_PATTERN = Pattern.compile("^(.*?)\\.(dom-as-me\\.domain\\.net|domain\\.net)$"); public static String extractShortName(String fqdn) { Matcher matcher = FQDN_PATTERN.matcher(fqdn); return matcher.find() ? matcher.group(1) : fqdn; } public static void main(String[] args) { String[] testCases = { "node.a.domain.net", "node.a.dev.domain.net", "node.a.sbx.domain.net", "node.a.b.domain.net", "node.a.dev.dom-as-me.domain.net", "node.a.dom-as-me.domain.net" }; for (String fqdn : testCases) { System.out.printf("%s => %s%n", fqdn, extractShortName(fqdn)); } } }
步骤3:Scala实现方案
利用Scala的集合方法简化逻辑:
object FQDNProcessor { private val suffixes = List("dom-as-me.domain.net", "domain.net") def extractShortName(fqdn: String): String = { suffixes.find(fqdn.endsWith) match { case Some(suffix) => fqdn.substring(0, fqdn.length - suffix.length - 1) case None => fqdn } } def main(args: Array[String]): Unit = { val testCases = List( "node.a.domain.net", "node.a.dev.domain.net", "node.a.sbx.domain.net", "node.a.b.domain.net", "node.a.dev.dom-as-me.domain.net", "node.a.dom-as-me.domain.net" ) testCases.foreach(fqdn => println(s"$fqdn => ${extractShortName(fqdn)}")) } }
扩展说明
- 新增后缀时,只需在
suffixes列表中添加(注意长后缀放在前面,确保优先匹配)。 - 如需大小写不敏感匹配,可将FQDN和后缀统一转为小写(或大写)后再判断。
内容的提问来源于stack exchange,提问作者happygopher
相关产品推荐
相关产品推荐

