【问题标题】:Regex to capture domain name from string including email addresses for specific tld's正则表达式从字符串中捕获域名,包括特定 tld 的电子邮件地址
【发布时间】:2017-06-15 03:18:33
【问题描述】:

我需要正则表达式,它可以从字符串中解析域名,包括来自电子邮件地址的域。我在 StackOverflow 上找到了以下正则表达式:

/(?:[\w-]+\.)+[\w-]+/

根据提供的演示,这很有名:https://regex101.com/r/aF1cY0/5

我在这里从 StackOverflow 上的另一个问题中得到了正则表达式:

How to get domain from a string using javascript regular expression

我想更改现有的正则表达式以仅匹配特定的 TLD(例如 com|net|biz)

由于我完全是 regex 的新手,因此我无法弄清楚该规定的放置位置。

非常感谢任何帮助。

【问题讨论】:

标签: javascript regex url subdomain


【解决方案1】:

/(?:[\w-]+\.)+(?:com|net|biz)/i

function check(){
  var str = prompt("URL example: ");
  var match = str.match(/(?:[\w-]+\.)+(?:com|net|biz)/i);
  if(match)
    alert("Your domain is: '" + match + "'");
  else
    alert("Sorry! Nothing matched!");
}
<button onclick="check()">TRY</button>

【讨论】:

    【解决方案2】:

    试试这个

    (?:[\w-]+\.)+com|net|biz
    

    【讨论】:

    • 这将匹配 "biz""net"。您应该将com|net|biz 分组到像(?:com|net|biz) 这样的非捕获组中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-09
    • 1970-01-01
    • 2015-11-08
    • 1970-01-01
    • 1970-01-01
    • 2022-01-26
    • 1970-01-01
    相关资源
    最近更新 更多