<body>
<textarea  id="txt"rows="10" cols="20">
</textarea>
<input type ="button" value ="测试" onclick ="_tests()"/>
</body>
<script language =javascript >
    function _tests()
    {
      var txts=document .getElementById("txt").value  ;
      var context=(/^[h|f]tp:www.[a-zA-Z0-9]+.[com|cn]$/g);
      while (res=context.exec(txts))
      {
        window .alert (res[0]);
      }
    }
   
    
</script>这个是匹配类似与www.baidu.com的url,结果为啥不对?

解决方案 »

  1.   

    <script>
    var p = /^www\.[a-zA-Z0-9]+\.(com|cn)$/g;
       var str="www.baidu.com";
       alert(str.match(p));
        p = /^(ht|f)tp:\/\/www\.[a-zA-Z0-9]+\.(com|cn)$/g;
       str="http://www.baidu.com";
       alert(str.match(p));</script>
      

  2.   

    http 不是htp
    匹配 . 在正则内需要转义 function _tests()
      {
      var txts=document .getElementById("txt").value ;
      var context=(/^((?:ht|f)tp:\/\/)?www\.[a-zA-Z0-9]+\.(?:com|cn)$/gi);
      while (res=context.exec(txts))
      {
      window .alert (res[0]);
      }
      }
      

  3.   

    这个只能匹配一行http://www.baidu.com
    要是再在下面写一行就检测不出来?有电子邮件的正则表达式吗?
      

  4.   

    var context=(/^((?:ht|f)tp:\/\/)?www\.[a-zA-Z0-9]+\.(?:com|cn)$/gim);
      

  5.   

    电子邮件(Email) ^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$
      

  6.   

    <!DOCTYPE HTML>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>test</title>
    <script src="jquery.js"></script>
    </head>
    <body>
    <textarea id="txt"rows="10" cols="20"></textarea>
    <input type ="button" value ="测试" onclick ="_tests()"/>
    <script type="text/javascript">
    function _tests(){
    var res,
    txts = document.getElementById("txt").value,
    context = (/^(?:http:|ftp:)?w{3}\.[a-zA-Z0-9]+\.(?:com|cn)$/);
    alert(context.exec(txts));
    }
    </script>
    </script>
    </body>
    </html>
      

  7.   

    你自己写的,alert (res[0])
      

  8.   

    都不明白[]是干嘛的。。这个是支持多行的<!DOCTYPE HTML>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>test</title>
    <script src="jquery.js"></script>
    </head>
    <body>
    <textarea id="txt"rows="10" cols="20"></textarea>
    <input type ="button" value ="测试" onclick ="_tests()"/>
    <script type="text/javascript">
    function _tests(){
    var res,
    txts = document.getElementById("txt").value,
    context = (/^(?:http:|ftp:)?w{3}\.[a-zA-Z0-9]+\.(?:com|cn)$/gm);
    while(res = context.exec(txts)){
    window.alert(res[0]);
    }
    }
    </script>
    </script>
    </body>
    </html>
      

  9.   

    你自己写的都不知道什么意思?
    res是exec查找的结果,为一个数组,取第一个元素(全匹配)打印出来。。