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

Regex模式用于获取URL结尾处正斜杠之间的数字

  •  3
  • mangocaptain  · 技术社区  · 9 年前

    我有一个字符串URL,我只想抓取“pokemon/”和“/”之间末尾的数字。

    " http://pokeapi.co/api/v2/pokemon/1/ "

    到目前为止我有这个-

    var regexPat = /\/d+\//
    "http://pokeapi.co/api/v2/pokemon/1/".match(regexPat)[0].slice(1,2) // returns 1
    

    有没有更有效的方法来做到这一点?

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

    您可以使用 /\/pokemon\/(\d+)\// 正则表达式:

    var s = "http://pokeapi.co/api/v2/pokemon/1/";
    var m = s.match(/\/pokemon\/(\d+)\//);
    if (m) {
      console.log(m[1]);
    }
    // or 
    console.log( 
      (res="http://pokeapi.co/api/v2/pokemon/1/".match(/\/pokemon\/(\d+)\//)) ? res[1] : ""
    );

    细节 :

    • \/pokemon\/ -文字文本 /pokemon/
    • (\d+) -捕获组1匹配1个或多个数字
    • \/ -一个 / 象征