用于查找基本 URL 的 Javascript 正则表达式 [英] Javascript regex to find a base URL

查看:35
本文介绍了用于查找基本 URL 的 Javascript 正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 JS 中的这个正则表达式很生气:

I'm going mad with this regex in JS:

var patt1=/^http(s)?:\/\/[a-z0-9-]+(.[a-z0-9-]+)*?(:[0-9]+)?(\/)?$/i;

如果我给出一个像http://www.eitb.com/servicios/concursos/516522/"这样的输入字符串,这个正则表达式应该返回NULL,因为在基本URL之后有一个文件夹".它适用于 PHP,但不适用于 Javascript,就像在这个脚本中一样:

If I give an input string like "http://www.eitb.com/servicios/concursos/516522/" this regex it's supossed to return NULL, because there are a "folder" after base URL. It works in PHP, but not in Javascript, like in this script:

<script type="text/javascript">
var str="http://www.eitb.com/servicios/concursos/516522/"; 
var patt1=/^http(s)?:\/\/[a-z0-9-]+(.[a-z0-9-]+)*?(:[0-9]+)?(\/)?$/i;
document.write(str.match(patt1));
</script>

它回来了

http://www.eitb.com/servicios/concursos/516522/,,/516522,,/ 

问题是:为什么它不起作用?如何使它工作?

The question is: why it is not working? How to make it work?

这个想法是在另一个函数中实现这个正则表达式,以便在传递的 URL 格式不正确时获取 NULL:

The idea is to implement this regex in another function to get NULL when the URL passed is not in the correct format:

http://www.eitb.com/ -> 正确http://www.eitb.com/something -> 不正确

http://www.eitb.com/ -> Correct http://www.eitb.com/something -> Incorrect

谢谢

推荐答案

我不是 javascript 专家,但习惯了 perl regexp,所以我会尝试一下;正则表达式中间的 . 可能需要进行转义,因为它可以映射 / 并破坏整个正则表达式.

I'm no javascript pro, but accustomed to perl regexp, so I'll give it a try; the . in the middle of the regexp might need to be escaped, as it can map a / and jinx the whole regexp.

试试这个:

var patt1=/^http(s)?:\/\/[a-z0-9-]+(\.[a-z0-9-]+)*?(:[0-9]+)?(\/)?$/i; 

这篇关于用于查找基本 URL 的 Javascript 正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆