尝试使用正则表达式在字符串数组中查找子字符串的 url



我有一个stringsarray。我需要在每个string上获取URL的值。我已经创建了一个function与Regex来完成这一点。它工作得很好,但有一个边缘情况我还没能涵盖。当没有任何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-/3n  })', 
  'https://url-goes-here-/4n  })', 
  'https://url-goes-here-/5n  })' ]

如何覆盖这种边缘情况&返回另一个array与所有的string在水平?

根据匹配函数文档中,它返回匹配的array,如果没有找到匹配,则返回null

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

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"]

最新更新