asy*_*ric 2 javascript regex regex-greedy regex-lookarounds
我正在尝试用正则表达式解决字符串匹配问题.我需要匹配此表单的网址:
http://soundcloud.com/okapi23/dont-turn-your-back/
Run Code Online (Sandbox Code Playgroud)
我需要"拒绝"此表单的网址:
http://soundcloud.com/okapi23/sets/happily-reversed/
Run Code Online (Sandbox Code Playgroud)
尾随'/'显然是可选的.
所以基本上:
到目前为止我提出的是http(s)?://(www\.)?soundcloud\.com/.+/(?!sets)\b(/.+)?失败的.
有什么建议?是否有任何库可以简化任务(例如,使尾部斜杠可选)?
假设OP想要测试以查看给定字符串是否包含满足以下要求的URL:
http:或https:.//soundcloud.com或//www.soundcloud.com."sets".[A-Za-z0-9]),并且多个单词由一个短划线或下划线分隔."/".这是一个经过测试的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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
885 次 |
| 最近记录: |