【问题标题】:Find matching strings from array with multiple params从具有多个参数的数组中查找匹配的字符串
【发布时间】:2021-10-10 10:01:09
【问题描述】:

不确定如何使用参数作为值和不同的参数计数来实现这样的搜索。看起来我需要Regexmatch。但参数在我的匹配(可能的 URL 数组)中没有硬编码 - 它们是动态的,参数值可以是 0、100、777 等。

例如,我有这样一个字符串数组要匹配:

[
'urlA/someId1',
'urlA/someId1/someSubUrlA/someId2',
'urlB/someId1/someId2'
'urlB/someId1/someSubUrlB/someId2'
]

ps:我可以编辑这个数组,例如用{} 等包围参数。

当我尝试搜索:http://example.com/urlA/100/someSubUrlA/200 它应该返回urlA/someId1/someSubUrlA/someId2

当我尝试搜索:http://example.com/urlA/150 它应该返回urlA/someId1

据我所知,我可以将Regex.match.find() 一起使用。但是我对如何使用自定义参数及其计数编写自定义匹配器感到困惑。在 JS 中是否有可能?

【问题讨论】:

  • 我猜你可以使用:github.com/pillarjs/path-to-regexp 例如,它也用于 react 路由器。
  • 我不完全明白你所说的多个参数是什么意思。我认为您宁愿指的是 url 中的域之后的所有内容。要找到它,您将遍历数组并在每个项目上执行正则表达式,可能会返回域之后的另一个数组。
  • 我认为这个问题需要更清晰的回答。

标签: javascript regex typescript ecmascript-6


【解决方案1】:

基本上你希望给定一个 url 来找到它的抽象表示。对吧?

let data = [
  'urlA/someId1',
  'urlA/someId1/someSubUrlA/someId2',
  'urlB/someId1/someId2',
  'urlB/someId1/someSubUrlB/someId2'
];

function finder(url) {
  let afterDomain = url.match(/http:\/\/[^\/]*\.[^\/]*\/(.*)/)[1];
  let matcher = afterDomain.replace(/\d+/g, "[^\/]+");
  return data.find(x => (new RegExp(matcher)).test(x))
}

finder("http://example.com/urlA/100/"); // "urlA/someId1"
finder("http://example.com/urlA/100/someSubUrlA/200"); // "urlA/someId1/someSubUrlA/someId2"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-18
    • 1970-01-01
    • 2019-03-10
    • 1970-01-01
    • 2020-08-07
    • 2014-06-26
    • 2022-10-14
    • 1970-01-01
    相关资源
    最近更新 更多