问题描述
请问js正则表达式,不能以/开始和结尾怎么写
解决方案
var re = /^([^/]([sS]*[^/])?)?$/;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");}不过相对来说,我更喜欢用两个正则来干这件事,简单明了: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");}
解决方案二:
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