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

查找没有特定单词的MP3 URL的正则表达式

  •  -1
  • NESHOM  · 技术社区  · 6 年前

    我想从一个没有特定单词的页面源中提取MP3 URL。

    下面是我用来搜索MP3 URL的正则表达式:

    https?:\/\/.+\.mp3
    

    效果不错。现在我想排除那些包含特定单词的URL。所以,我需要的URL中没有特定的单词。

    我怎样才能排除 http .mp3 ?

    我将在QT中用C++来使用,但是只要它与 https://regex101.com/ 很好。

    2 回复  |  直到 6 年前
        1
  •  3
  •   Nick SamSmith1986    6 年前

    如果要“排除那些 没有 它们中的一个特定单词”,您可以对该单词使用正向前视(前面有一些字符),例如。

    (?=.*Sing)
    

    在JavaScript中:

    const word = 'Sing';
    const urls = ['http://I_like_to_sing.mp3', 'http://Another_song.mp3'];
    let regex = new RegExp('https?:\/\/(?=.*' + word + ').+\.mp3', 'i');
    console.log(urls.filter(v => v.match(regex)));

    在PHP中

    $word = 'Sing';
    $urls = ['http://I_like_to_sing.mp3', 'http://Another_song.mp3'];
    $regex = "/https?:\/\/(?=.*$word).+\.mp3/i";
    print_r(array_filter($urls, function ($v) use ($regex) { return preg_match($regex, $v); }));
    

    输出:

    Array ( 
        [0] => http://I_like_to_sing.mp3 
    )
    

    Demo on 3v4l.org

    更新

    排除那些URL 在它们中有一个特定的词,你可以用一个否定的先行词来代替。

    (?![^.]*Sing)
    

    我们使用 [^.] 确保单词出现 之前 这个 .mp3 部分。下面是一个PHP演示:

    $word = 'Song';
    $string = "some words http://I_like_to_sing.mp3 and then some other words http://Another_song.mp3 and some words at the end...";
    $regex = "/(https?:\/\/(?![^.]*$word).+?\.mp3)/i";
    preg_match_all($regex, $string, $matches);
    print_r($matches[1]);
    

    输出:

    Array ( 
        [0] => http://I_like_to_sing.mp3
    )
    

    Demo on 3v4l.org

        2
  •  0
  •   Franco Gil    6 年前

    我希望这是一个有用的答案。

    这是一个启用了用例的正则表达式 Python 3 . 所以如果你想排除 HTTP协议 和; MP3 你可以这样做。

    import re
    
    ref = "http://www.some_undesired_text_018/m102/1-225x338.mp3"
    
    _del = re.findall(r'https?(.+)\.mp3', ref)[0]
    
    out = ref.replace(_del, "")
    
    #_del will contain the undesired word