代码之家  ›  专栏  ›  技术社区  ›  Ryan Peschel

如何在regex中捕获子域?

  •  2
  • Ryan Peschel  · 技术社区  · 5 年前

    我正试图从tumblr中提取用户名。也就是说,regex应该匹配 asdf 在以下测试字符串中:

    https://asdf.tumblr.com/
    http://asdf.tumblr.com/faq
    www.asdf.tumblr.com/
    asdf.tumblr.com
    

    .*[\/|\.](.*)\.tumblr\.com.*
    

    但是,这无法捕获最后一个组( asdf.tumblr.com ). 我试图修改它,但没有用。能做到吗?

    1 回复  |  直到 5 年前
        1
  •  2
  •   anubhava    5 年前

    您可以在Javascript中使用此regex:

    /[^.\/]+(?=\.tumblr\.com)/i
    

    RegEx Demo

    正则表达式详细信息:

    • [^.\/]+ :匹配1个或多个非 . /
    • (?=\.tumblr\.com) :积极展望,确保我们 .tumblr.com 在下一个位置

    let x = /([^.\/]+)(?=\.tumblr\.com)/;
    let y = "https://asdf.tumblr.com";
    
    console.log( y.match(x)[1] );