将正则表达式与正则表达式结合使用

我正在编写一个正则表达式来检测一个字符串是否以有效的协议开头——现在可以说它可以是httpftp—。协议后必须跟://, 和一个或多个字符,字符串中不能有空格,忽略大小写。

我有这个正则表达式可以做所有事情,除了检查字符串中的空格:

const regex = new RegExp('^(http|ftp)(://)((?=[^/])(?=.+))', 'i');
const urlHasProtocol = regex.test(string);
^(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

那些必须通过:

http://example.com
http://example.com/path1/path2?hello=1&hello=2
http://a
http://abc

那些必须失败:

http:/example.com
http://exampl e.com
http:// exampl e.com
http://example.com // Trailing space
http:// example.com
http:///www.example.com

我正在尝试为空格添加规则。我正在尝试向前看,检查中间或末尾是否有一个或多个空格:(?=[^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

但这不能正常工作。

欢迎任何建议

回答

仅使用您显示的示例,请您尝试以下操作。

^(https?|ftp)://(?!W*www.)S+$

这是上述正则表达式的在线演示

说明:为上述正则表达式添加详细说明。

^(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.


以上是将正则表达式与正则表达式结合使用的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>