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

正则表达式:在第一个反斜杠出现后查找特定单词

  •  1
  • Marc  · 技术社区  · 2 年前

    我想用正则表达式在第一次出现“/”之后查找单词“bacon”。

    例如:

    应返回true:

    console.log('1 - ', myRegexFunction('www.bacondelivery.com/weekly-bacon-delivery/'));
    console.log('2 - ', myRegexFunction('www.bacondelivery.com/daily-bacon-delivery/'));
    console.log('3 - ', myRegexFunction('www.bacondelivery.com/bacon-of-the-month-club/'));
    

    应返回false:

    console.log('4 - ', myRegexFunction('www.bacondelivery.com/'));
    console.log('5 - ', myRegexFunction('www.bacondelivery.com/?some_param'));
    console.log('6 - ', myRegexFunction('www.bacondelivery.com/about/'));
    console.log('7 - ', myRegexFunction('www.bacondelivery.com/contact-us/'));
    

    以下是我目前拥有的:

    function myRegexFunction(url) {
      var regex = new RegExp("^([a-z0-9]{5,})$");
      if (regex.test(url)) {
          return true;
      } else {
          return false;
      }
    }
    

    谢谢

    4 回复  |  直到 2 年前
        1
  •  3
  •   anubhava    2 年前

    您可以将此正则表达式用于:

    ^[^\/]+\/[^\/]*\bbacon\b.*
    

    RegEx Demo

    正则表达式详细信息:

    • ^ :开始
    • [^\/]+ :匹配一个或多个非 /
    • \/ :匹配a /
    • [^\/]* :匹配0个或更多非 /
    • \bbacon\b :匹配完整单词 bacon
    • .* :匹配此行的剩余文本

    代码:

    function myRegexFunction(url) {
      const regex = /^[^\/]+\/[^\/]*\bbacon\b.*/;
      return regex.test(url);
    }
    
    console.log('1 - ', myRegexFunction('www.bacondelivery.com/weekly-bacon-delivery/'));
    
    console.log('2 - ', myRegexFunction('www.bacondelivery.com/daily-bacon-delivery/'));
    console.log('3 - ', myRegexFunction('www.bacondelivery.com/bacon-of-the-month-club/'));
    
    console.log('4 - ', myRegexFunction('www.bacondelivery.com/'));
    console.log('5 - ', myRegexFunction('www.bacondelivery.com/?some_param'));
    console.log('6 - ', myRegexFunction('www.bacondelivery.com/about/'));
    console.log('7 - ', myRegexFunction('www.bacondelivery.com/contact-us/'));
        2
  •  2
  •   lemon    2 年前

    尝试使用以下正则表达式:

    \/.*\bbacon\b
    

    如果你找到一个匹配项,这意味着你的url中有这个词。如果需要在不区分大小写的情况下匹配,那么可以使用“i”修饰符。

    正则表达式解释:

    • \/ :斜杠
    • .*
    • \bbacon\b :你的热门词汇在词界之间

    查看演示 here .


    编辑 :如果你想配你的培根“ 单词 “特别是在第一次发生后,检查anubhava的回答。

        3
  •  1
  •   Konrad    2 年前

    你试过这个吗?

    /\/.*bacon/
    
        4
  •  1
  •   Jon    2 年前

    我会用一个简单的例子: const regex = /\/.*(bacon)/

    function myRegexFunction(url) {
      var regex = /\/.*(bacon)/;
      if (regex.test(url)) {
          return true;
      } else {
          return false;
      }
    }
    
    • \/ 在a之后匹配 /
    • .* 0到n个字符
    • (bacon) 您的模式(括号是可选的)

    请注意,如果您的链接是 http://baconurl/…