代码之家  ›  专栏  ›  技术社区  ›  Kawd

在模式最后一次出现之前的所有操作

  •  -2
  • Kawd  · 技术社区  · 6 年前

    给定以下字符串:

    '/a/xxx/b/c/xxx/xxx/d/e/xxx/xxx/f/g'
    '/a/xxx/b/c/xxx/xxx/d/e/xxx/xxx/f/'
    '/a/xxx/b/c/xxx/xxx/d/e/xxx/xxx/f'
    '/a/xxx/b/c/xxx/xxx/d/e/xxx/xxx/f/g/xxx/xxx'
    

    我在找一个能匹配的正则表达式

    /a/xxx/b/c/xxx/xxx/d/e/xxx/xxx/f
    

    对于上述所有字符串

    也就是说,Match 直到最后一次出现此模式之前的所有内容:

    正斜杠或字符串开头然后xxx然后正斜杠然后不等于xxx然后正斜杠或字符串结尾

    我不知道如何将上述模式转换为regex。

    这个 .*\/ 我尝试的模式不能解决问题。

    1 回复  |  直到 6 年前
        1
  •  1
  •   Wiktor Stribiżew    6 年前

    /(?:.*\/)?xxx\/(?!xxx(?![^\/]))[^/]*(?=$|\/)/
    

    regex demo

    • (?:.*\/)?
      • .*
      • \/ /
    • xxx\/ xxx/
    • (?!xxx(?![^\/])) xxx
    • [^/]*
    • (?=$|\/)

    var strs = ['/a/xxx/b/c/xxx/xxx/d/e/xxx/xxx/f/g','/a/xxx/b/c/xxx/xxx/d/e/xxx/xxx/f/','/a/xxx/b/c/xxx/xxx/d/e/xxx/xxx/f','/a/xxx/b/c/xxx/xxx/d/e/xxx/xxx/f/g/xxx/xxx','/xxx/f/g','xxx/f/g','a/xxx/f/g','/a/xxx/f/g','/a/xxx/b/c/xxx/xxx/d/e/xxx/gggxxxd/f/gxxxf/'];
    var rx = /(?:.*\/)?xxx\/(?!xxx(?![^\/]))[^/]*(?=$|\/)/;
    for (var s of strs) {
      console.log(s, "=>", s.match(rx)[0]);
    }