firefoxeye
2011-12-19 18:06 阅读 1.5k

请问js正则表达式,不能以/开始和结尾怎么写

请问js正则表达式,不能以/开始和结尾怎么写

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

2条回答 默认 最新

  • 已采纳
    cyrilluce cyrilluce 2011-12-19 20:39

    [code="js"]
    var re = /^(^\/?)?$/;

    var cases = [
    ["", true],
    [" ", true],
    ["a", true],
    ["abc", true],
    ["a/c", true],
    [" /b/ ", true],
    ["/", false],
    ["/bc", false],
    ["ab/", false],
    ["/b/", false],
    ["//", false]
    ];

    var i, err=false;
    for(i=0; i<cases.length; i++){
    if(re.test(cases[i][0]) !== cases[i][1]){
    err=true;
    alert("fail: "+cases[i].join(","));
    }
    }
    if(!err){
    alert("pass");
    }
    [/code]

    不过相对来说,我更喜欢用两个正则来干这件事,简单明了:
    [code="js"]
    var test = function(str){
    if(/^\//.test(str) || /\/$/.test(str)){
    return false;
    }
    return true;
    };

    var cases = [
    ["", true],
    [" ", true],
    ["a", true],
    ["abc", true],
    ["a/c", true],
    [" /b/ ", true],
    ["/", false],
    ["/bc", false],
    ["ab/", false],
    ["/b/", false],
    ["//", false]
    ];

    var i, err=false;
    for(i=0; i<cases.length; i++){
    if(test(cases[i][0]) !== cases[i][1]){
    err=true;
    alert("fail: "+cases[i].join(","));
    }
    }
    if(!err){
    alert("pass");
    }
    [/code]

    点赞 评论 复制链接分享
  • easyroom easyroom 2011-12-19 20:35

    function matchDemo(){
    var s;
    var re = new RegExp("d(b+)(d)","ig");
    var str = "cdbBdbsbdbdz";
    var arr = re.exec(str);
    s = "$1 contains: " + RegExp.$1 + "\n";
    s += "$2 contains: " + RegExp.$2 + "\n";
    s += "$3 contains: " + RegExp.$3;
    return(s);
    }

    如果需要更详细的就找一个js的api看 RegExp

    点赞 评论 复制链接分享

相关推荐