正则表达式学习(二)

来源:互联网 发布:smtp使用的端口号为 编辑:程序博客网 时间:2024/04/29 05:30

<html>
<head>
<title>正则表达式学习(2)</title>
<script type="text/javascript">
    /*------String中的方法和正则表达式的搭配使用------*/
    var re;
    var str = "---abc123----";
    //将str中的'-'全部替换成'#'
    //re = /-/;
    //alert(str.replace(re,"#"));//#--abc123----,并没有达到目的
    //此时需要改写正则表达式的标志参数,将其设置为g,即全文匹配
    //re = /-/g;
    //alert(str.replace(re,"#"));//###abc123####,达到了目的
    //将字符串中的连续的'-'替换成单个'#'
    //re = /-+/g;
    //alert(str.replace(re, "#"));//#abc123#
    str = "    asdfas fdasdf aasdf   ";
    //去除字符串前后的空格
    //re = /^/s+|/s+$/g;
    //alert("|"+str.replace(re, "")+"|");
    function trim(s){
        var re = /^/s+|/s+$/g;
        return str.replace(re, "");
    }
    //alert(trim(str));
    //str = "123,345,24";
    //alert(str.split(","));
    //str = prompt("输入单词与中文释义(空格分开):","");
    //alert(str.split(//s+/));
    //str = prompt("输入日期(如2010-12-1):","");
    /**
     * [^0-9]表示匹配非数字类型的字符
     */
    /*
    var year = str.split(/[^0-9]+/)[0],
            month = str.split(/[^0-9]+/)[1],
            day = str.split(/[^0-9]+/)[2];
    alert(year + "年" + month + "月" + day + "日");
    */
    //str="My name is Kenshin and my age is 23 , 234!";
    //alert(str.search("is")); //等价于str.indexOf("is");
    //alert(str.indexOf("is"));
    //alert(str.search(//d+/));
    //str = "Windows 7.0";
    /**
     * .表示匹配任意字符(除换行符以外)
     * /^([a-z]+)/s+(/d+).(/d+)$/i;
     */
    //re = /^([a-z]+)/s+(/d+).(/d+)$/i;
    str = "Windows 7-0";
    //alert(re.test(str));//true
    re = /^([a-z]+)/s+(/d+)/.(/d+)$/i;
    alert(re.test(str));//false
</script>
<style type="text/css">
</style>
</head>
<body>
    <h1>正则表达式学习(2)</h1>
</body>
</html>

原创粉丝点击