You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Google App Script中用正则提取无二级域名的第二个域名失败求助

问题:提取字符串中第二个无www前缀的域名失败

示例HTML字符串如下,包含duckduckgo.com和chicaspoderosas.org两个域名:

<a rel="nofollow" class="result__a" href="//duckduckgo.com/l/?uddg=https%3A%2F%2Fchicaspoderosas.org%2Fabout%2F&amp;rut=6df21641031fd7b57d82fcdbc2312bc4b27034927655759d8e270840fae4fab1">ABOUT - Chicas Poderosas</a>

当前使用的正则表达式仅能提取带www子域名的第二个域名:

var regExp = new RegExp("(www.[a-z]+.[a-z]+.[a-z])", "gi");

但当第二个域名没有www前缀时无法匹配,请问问题出在哪里?


问题原因与解决方案

问题根源

你的正则存在三个关键限制:

  1. 强制绑定www前缀:正则开头硬编码了www.,没有www的域名直接不符合匹配条件,自然提取不到。
  2. 固定三级域名结构:www.[a-z]+.[a-z]+.[a-z]要求域名必须是www.xxx.yyy.zzz这种三级格式,但示例中的chicaspoderosas.org是二级域名(xxx.yyy),结构不匹配,所以无法命中。
  3. 字符范围过窄:只允许小写字母,实际域名还支持数字、连字符(虽加了gi忽略大小写,但字符类未覆盖合法字符)。

解决方案

目标域名存在于uddg参数的URL编码值中,最可靠的方式是先定位这个参数区域,再提取域名,避免全局匹配的不确定性:

方法1:分步提取(更灵活)

const htmlStr = '<a rel="nofollow" class="result__a" href="//duckduckgo.com/l/?uddg=https%3A%2F%2Fchicaspoderosas.org%2Fabout%2F&amp;rut=6df21641031fd7b57d82fcdbc2312bc4b27034927655759d8e270840fae4fab1">ABOUT - Chicas Poderosas</a>';

// 第一步:匹配uddg参数的取值
const uddgMatch = htmlStr.match(/uddg=([^&]+)/);
if (uddgMatch) {
  // 第二步:解码URL编码的字符串
  const decodedUrl = decodeURIComponent(uddgMatch[1]);
  // 第三步:提取域名(支持带/不带http(s)前缀、带/不带子域名)
  const domainMatch = decodedUrl.match(/^(https?:\/\/)?([^\/]+)/);
  if (domainMatch) {
    const targetDomain = domainMatch[2];
    console.log(targetDomain); // 输出 chicaspoderosas.org
  }
}

方法2:单正则直接匹配(更简洁)

const htmlStr = '<a rel="nofollow" class="result__a" href="//duckduckgo.com/l/?uddg=https%3A%2F%2Fchicaspoderosas.org%2Fabout%2F&amp;rut=6df21641031fd7b57d82fcdbc2312bc4b27034927655759d8e270840fae4fab1">ABOUT - Chicas Poderosas</a>';

const regExp = /uddg=https%3A%2F%2F([^%]+)/i;
const match = htmlStr.match(regExp);
if (match) {
  const targetDomain = match[1];
  console.log(targetDomain); // 输出 chicaspoderosas.org
}

通用域名匹配正则(可选)

如果需要匹配任意合法域名(带/不带子域名),可以用这个更严谨的正则:

const domainReg = /^(https?:\/\/)?(([a-zA-Z0-9-]+\.)+[a-zA-Z]{2,})/;

内容的提问来源于stack exchange,提问作者Ben Shaw

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 22:12:15