【问题标题】:How match sub-hostname is from main-hostname through regex in Java子主机名如何通过Java中的正则表达式从主主机名匹配
【发布时间】:2016-06-20 04:27:43
【问题描述】:

像这样。主机名匹配“*”。

// ----------------------
*.example.com
    www.example.com  -> pass
    img.example.com  -> pass
    www.example2.com -> fail

// ----------------------
www.example.com
    www.example.com -> pass
    img.example.com -> fail

所有顶级域“com”匹配。

enter code here
// -----------------------
*.com
    www.a.com -> pass
    www.b.com -> pass
    www.c.org -> fail

或简单的所有域。

//------------------------
*
    www.a.com -> pass
    img.b.com -> pass
    c.org     -> pass

【问题讨论】:

  • 也许向我们展示您对正则表达式的尝试,其他人可能更容易在需要更正或可以使用优化的地方提供帮助?

标签: java regex dns


【解决方案1】:

您可以通过以下方式将所有匹配项变成正则表达式:

  • * 替换为.*
  • \.替换.(在java字符串中它需要是\\.

然后您可以使用以下代码来匹配要测试的字符串:

Pattern p = Pattern.compile(".*\\.example\\.com");
Matcher m = p.matcher("www.example.com");
boolean b = m.matches();

您的匹配字符串:

  • *.example.com -> .*\.example\.com
  • www.example.com -> www\.example\.com
  • *.com -> .*\.com
  • * -> .*

【讨论】:

  • 太棒了!这种方法对我有用。谢谢! "*.example.com".replace(".", "\\.").replace("*", ".*")
猜你喜欢
  • 1970-01-01
  • 2021-03-13
  • 2010-10-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-11
  • 1970-01-01
相关资源
最近更新 更多