【问题标题】:Get part of url with conditions获取带有条件的部分 url
【发布时间】:2018-07-15 02:03:42
【问题描述】:

基于此示例:http://example.com/cat1/tag/this%20is%20page/cat2,我需要创建一个正则表达式以获取 /tag/<nextSegment>,仅当此模式被其他段跟随或之前,而不是单独的。

我需要的结果始终是:http://example.com/tag/<fowardSegment> 仅当 /tag/<fowardSegment> 位于不允许的其他段或字符之前或之后。

我尝试使用此正则表达式:((?:/[A-Za-z0-9-]+)+)?(/tag/[A-Za-z0-9-%]+)+(/.*)?,但该模式在单独使用时也会被捕获(您可以在链接中看到最后一个示例字符串)。

【问题讨论】:

  • 我不明白你的问题。它可能还会受益于一些示例字符串(匹配和不匹配)。
  • 对不起,我在链接中添加了一些示例字符串..
  • 请在问题中包含它,链接内容经常被忽略。
  • 你能发布预期的结果吗
  • 哪些字符串应该匹配,哪些不应该?请将这些集合添加到问题中。

标签: regex regex-negation regex-lookarounds regex-group


【解决方案1】:

也许你想要的是这个:/(?<=https?:\/\/.*)((?:\/[\w]+)*)((?:\/tag)(?:\/[\w%?=.-]+){2,})$/

编辑

正如我在下面的 cmets 中了解到的需要匹配的额外的:

/(?<=https?:\/\/.*|[\w_.]+)(?:((?:\/[\w]+)+)((?:\/tag)(?:\/[\w%?=.-]+))|((?:\/[\w]+))*((?:\/tag)(?:\/[\w%?=.-]+){2,}))$/

JS 中的一个示例用法:

let regex = /(?<=https?:\/\/.*|[\w_.]+)(?:((?:\/[\w]+)+)((?:\/tag)(?:\/[\w%?=.-]+))|((?:\/[\w]+))*((?:\/tag)(?:\/[\w%?=.-]+){2,}))$/,
  examples = ["http://example.com/cat1/subcat3/subcat4/tag/this%20is%20page/asdasda?start=130/asdasdasd", // #Should Match
    "http://example.com/cat1/subcat3/subcat4/tag/this%20is%20pageasdasd", // Should Match
    "example.it/news/tag/this%is%20n%page?adsadsadasd", // Should Match
    "http://example.com/tag/thispage/asdasdasd.-?asds=", // Should Match
    "http://example.com/tag/this%20is%20page/asdasd", // Should Match
    "http://example.com/tag/this", // Should Not Match
    "/tag/this/asdads" // Should Not Match
  ]

examples.forEach((example) => {
  if (example.match(regex)) {
    let matches = regex.exec(example),
        category = matches[1] !== undefined ? matches[1] : matches[3] !== undefined ? matches[3] : "No category",
        tag = matches[2] === undefined ? matches[4] : matches[2];
        
    console.log(`Full String: "${example}"\nCategory: "${category}"\nTag: "${tag}"`)
  }
})

查看Regex101

【讨论】:

  • 一点也不。如果您看到我的示例:link to example,除了最后一个不能匹配的字符串示例之外,我完全匹配,因为 /tag/ 之前或之后没有其他段或字符。
  • @Kouga 查看我的编辑,它现在应该做你想做的事了
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-08-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-18
  • 2011-07-20
  • 2023-04-04
相关资源
最近更新 更多