为我工作的开发人员编写了一个正则表达式,用于在用户输入网址时检查有效的网址。到目前为止它工作得非常好,除了它不识别IP地址这一事实。
url = url.match(/(http\:\/\/)?[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\S*)?/)
正确:
Given: http://www.mywebsite.com/index.cfm?do=something
Result: http://www.mywebsite.com/index.cfm?do=something
不正确:
Given: http://64.200.10.50/index.cfm?do=something
Result: http://index.cfm?do=something
Should be: http://64.200.10.50/index.cfm?do=something
我如何修改正则表达式以考虑IP地址?
由于
答案 0 :(得分:4)
简单的解决方案:只允许除https://和第一个/之间的/和空格之外的所有内容。这样你也将支持单级域名,ipv6地址等
/^https?\:\/\/[^\/\s]+(\/.*)?$/