gpt4 book ai didi

java - 用于匹配 mp3 URL 的正则表达式

转载 作者:行者123 更新时间:2023-12-02 00:18:40 24 4
gpt4 key购买 nike

如何使用 REGEX 获取 mp3 url?

这个 mp3 url,例如:

https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3

This is a what I've tried so far but I want it to only accept a url with '.mp3' on the end.

(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]

最佳答案

这个表达式可能会传递您想要的输入:

^(https?|ftp|file):\/\/(www.)?(.*?)\.(mp3)$

如果你想给它添加更多的边界,你可以这样做。例如,您可以添加一个字符列表而不是 .*.

enter image description here

我添加了几个捕获组,以便在必要时调用。

正则表达式

如果这不是您想要的表达式,您可以在 regex101.com 中修改/更改您的表达式.

正则表达式电路

您还可以在 jex.im 中可视化您的表情:

enter image description here

const regex = /^(https?|ftp|file):\/\/(www.)?(.*?)\.(mp3)$/gm;
const str = `https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3
http://soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3
http://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3
ftp://soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3
file://localhost/examples/mp3/SoundHelix-Song-1.mp3
file://localhost/examples/mp3/SoundHelix-Song-1.wav
file://localhost/examples/mp3/SoundHelix-Song-1.avi
file://localhost/examples/mp3/SoundHelix-Song-1.m4a`;
let m;

while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}

// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
console.log(`Found match, group ${groupIndex}: ${match}`);
});
}

Java 测试

import java.util.regex.Matcher;
import java.util.regex.Pattern;

final String regex = "^(https?|ftp|file):\\/\\/(www.)?(.*?)\\.(mp3)$";
final String string = "https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3\n"
+ "http://soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3\n"
+ "http://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3\n"
+ "ftp://soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3\n"
+ "file://localhost/examples/mp3/SoundHelix-Song-1.mp3\n"
+ "file://localhost/examples/mp3/SoundHelix-Song-1.wav\n"
+ "file://localhost/examples/mp3/SoundHelix-Song-1.avi\n"
+ "file://localhost/examples/mp3/SoundHelix-Song-1.m4a";

final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);

while (matcher.find()) {
System.out.println("Full match: " + matcher.group(0));
for (int i = 1; i <= matcher.groupCount(); i++) {
System.out.println("Group " + i + ": " + matcher.group(i));
}
}

关于java - 用于匹配 mp3 URL 的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56194746/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com