【问题标题】:Trying to use regex to find a sub-string's urls in array of strings尝试使用正则表达式在字符串数组中查找子字符串的 url
【发布时间】:2021-01-14 22:19:18
【问题描述】:

我有一个 arraystrings。我需要在每个string 上获取URL 的值。我创建了一个functionRegex 来完成此任务。它工作正常,但有一个我无法涵盖的边缘情况。当没有任何URL: 的值时,我得到错误:Cannot read property '1' of null

这是我的代码:

const arrStr = [
  `describe
    url: https://url-goes-here-/1,
         https://url-goes-here-/2,
         https://url-goes-here-/3
  });`
  ,
  `
  before(() => {
    url: https://url-goes-here-/4
  });
  `,
  `
  before(() => {
    url: https://url-goes-here-/5
  });
  `,
  `describe
    // nothing http link here
  });
  `
]

const getXrayUrl = str => str.match(/url:([^;]+)/)[1].trim().split('(')[0]; // cannot read property '1' of null

const allXrayUrls = arrStr.map(item => getXrayUrl(item));

如果我从array 中删除没有URL 值的string,我会得到以下输出:

[ 'https://url-goes-here-/1,\n         https://url-goes-here-/2,\n         https://url-goes-here-/3\n  })', 
  'https://url-goes-here-/4\n  })', 
  'https://url-goes-here-/5\n  })' ]

我如何覆盖这个边缘情况并返回另一个 array 以及关卡中的所有 string

【问题讨论】:

  • 因为如果match不匹配,则返回null,而不是空数组。尝试获取 null1 属性会引发错误(因为 null 不是对象)。因此,如果 match 返回 null,则替换为空数组,例如(str.match(/url:([^;]+)/) || [])[1] 所以如果没有匹配,表达式返回 undefined 而不是抛出错误。

标签: javascript arrays regex ecmascript-6


【解决方案1】:

根据ma​​tch函数documentation,它返回一个匹配的array,如果没有找到匹配则返回null

如果您需要处理缺少 URL 属性的情况,请在访问捕获组之前检查匹配数组是否为空,如下所示:

const match = str.match(/url:\s*([^;]+)\n/)
// in case no match retrun empty string
// split the match on , to handle multi URL case
const url = match? match[1].split(",").map(item => item.trim()) : [""];

过滤匹配结果后删除空值如下:

arrStr.map(getXrayUrl).flat().filter(item => item !== "");

所以最终解决方案如下:

const arrStr = [
  `describe
    url: https://url-goes-here-/1,
         https://url-goes-here-/2,
         https://url-goes-here-/3
  });`
  ,
  `
  before(() => {
    url: https://url-goes-here-/4
  });
  `,
  `
  before(() => {
    url: https://url-goes-here-/5
  });
  `,
  `describe
    // nothing http link here
  });
  ` 
]

const getXrayUrl = str => {
    const match = str.match(/url:\s*([^;]+)\n/)
    // in case no match retrun empty string
    // split the match on , to handle multi URL case
    return match? match[1].split(",").map(item => item.trim()) : [""];
}

const allXrayUrls = arrStr.map(getXrayUrl).flat().filter(item => item !== "");

console.log(allXrayUrls)

控制台输出:

["https://url-goes-here-/1", "https://url-goes-here-/2", "https://url-goes-here-/3", "https://url-goes-here-/4", "https://url-goes-here-/5"]

【讨论】:

  • 谢谢,它就像一个魅力兄弟!你知道如何让前三个URLs 也作为数组返回吗? ``` [ "url-goes-here-/1", "url-goes-here-/2", "url-goes-here-/3", "url-goes-here-/4", "url-goes-here-/5" ]
  • @ManuelAbascal 检查更新的解决方案是否符合您的要求?
  • 是的!但是,数组的第一项包含三个URL而不是一个,怎么能展平呢?
  • 我已经更新了解决这个问题的解决方案,试试吧
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-11
  • 1970-01-01
  • 2017-07-04
  • 1970-01-01
相关资源
最近更新 更多