我正在编写一个正则表达式来检测一个字符串是否以有效的协议开头——现在可以说它可以是http
或ftp—
。协议后必须跟://
, 和一个或多个字符,字符串中不能有空格,忽略大小写。
我有这个正则表达式可以做所有事情,除了检查字符串中的空格:
const regex = new RegExp('^(http|ftp)(://)((?=[^/])(?=.+))', 'i');
const urlHasProtocol = regex.test(string);
Run Code Online (Sandbox Code Playgroud)
^(http|ftp) — checks for http or ftp at the beginning
(://) — is followed by "://"
((?=[^/])(?=.+)) — is followed by a string that
(?=[^/]) — doesnt start with "/"
(?=.+) — has one or more characters
Run Code Online (Sandbox Code Playgroud)
那些必须通过:
http://example.com
http://example.com/path1/path2?hello=1&hello=2
http://a
http://abc
Run Code Online (Sandbox Code Playgroud)
那些必须失败:
http:/example.com
http://exampl e.com
http:// exampl e.com
http://example.com // Trailing space
http:// example.com
http:///www.example.com
Run Code Online (Sandbox Code Playgroud)
我正在尝试为空格添加规则。我正在尝试向前看,检查中间或末尾是否有一个或多个空格:(?=[^s+$])
^(http|ftp) — checks for http or ftp at the beginning
(://) — is followed by "://"
((?=[^/])(?=.+)) — is followed by a string that
(?=[^/]) — doesnt start with "/"
(?=.+) — has one or more characters
Run Code Online (Sandbox Code Playgroud)
但这不能正常工作。
欢迎任何建议
仅使用您显示的示例,请您尝试以下操作。
^(https?|ftp):\/\/(?!\W*www\.)\S+$
Run Code Online (Sandbox Code Playgroud)
说明:为上述正则表达式添加详细说明。
^(https?|ftp): ##Checking if value starts with http(s optional here to match http/https) OR ftp.
\/\/ ##Matching 2 // here.
(?!\W*www\.) ##Checking a negative lookahead to see if \W matches any non-word character (equivalent to [^a-zA-Z0-9_]) then www with a dot is NOT in further values.
\S+$ ##matches any non-whitespace character will end of the value here.
Run Code Online (Sandbox Code Playgroud)