假设 OP 想要测试给定的字符串是否包含满足以下要求的 URL:
- URL 方案必须是
http:
或https:
。
- URL 权限必须是
//soundcloud.com
或//www.soundcloud.com
。
- URL 路径必须存在并且必须包含 2 或 3 个路径段。
- 第二个路径段不能是:
"sets"
。
- 每个路径段必须由一个或多个仅由字母数字字符 (
[A-Za-z0-9]
) 组成的“单词”组成,并且多个单词由一个短划线或下划线分隔。
- URL 必须没有查询或片段组件。
- URL 路径可能以可选的
"/"
.
- URL 应该不区分大小写。
这是一个经过测试的 JavaScript 函数(带有完全注释的正则表达式),它可以解决问题:
function isValidCustomUrl(text) {
/* Here is the regex commented in free-spacing mode:
# Match specific URL having non-"sets" 2nd path segment.
^ # Anchor to start of string.
https?: # URL Scheme (http or https).
// # Begin URL Authority.
(?:www\.)? # Optional www subdomain.
soundcloud\.com # URL DNS domain.
/ # 1st path segment (can be: "sets").
[A-Za-z0-9]+ # 1st word-portion (required).
(?: # Zero or more extra word portions.
[-_] # only if separated by one - or _.
[A-Za-z0-9]+ # Additional word-portion.
)* # Zero or more extra word portions.
(?!/sets(?:/|$)) # Assert 2nd segment not "sets".
(?: # 2nd and 3rd path segments.
/ # Additional path segment.
[A-Za-z0-9]+ # 1st word-portion.
(?: # Zero or more extra word portions.
[-_] # only if separated by one - or _.
[A-Za-z0-9]+ # Additional word-portion.
)* # Zero or more extra word portions.
){1,2} # 2nd path segment required, 3rd optional.
/? # URL may end with optional /.
$ # Anchor to end of string.
*/
// Same regex in javascript syntax:
var re = /^https?:\/\/(?:www\.)?soundcloud\.com\/[A-Za-z0-9]+(?:[-_][A-Za-z0-9]+)*(?!\/sets(?:\/|$))(?:\/[A-Za-z0-9]+(?:[-_][A-Za-z0-9]+)*){1,2}\/?$/i;
if (re.test(text)) return true;
return false;
}