日期:2014-05-16  浏览次数:20354 次

求一个正则。关于取第3个逗号前的数据。
比如str   =   "123,234,345,456,567... "

怎么用正则取得 "123,234,345 ",即第3个逗号前的数据串

------解决方案--------------------
<script type= "text/javascript ">
var str = "123,234,345,456,567... "
alert(str.replace(/^([^,]*?,[^,]*?,[^,]*?),(.*?)$/, "$1 "))
</script>
------解决方案--------------------
alert(/^((?:[^,]*,){2}[^,]*)/.test(str)?RegExp.$1: "Nothing Match! ");
------解决方案--------------------
<script type= "text/javascript ">
str = "123,234,345,456,567... "
id=str.match(/^([^,]+[,]){3}/g)
s=id[0].substr(0, 11);
alert(s)
</script>

------解决方案--------------------
var str = "123,234,345,456,567,678 "
alert(str.match(/\d+/g).slice(0,3).join( ", "));
~~~~
这是最好的感觉,忘了slice方法了
------解决方案--------------------
var str = "123,234,345,456,567, ";
var sr = [];
var a = [str];
for(var i=1;i <16;i++)
a = a.concat(a);
str = a.join( ' ');
sr[sr.length] = [ "测试字数: ",str.length].join( ' ');

//方法1
var ts = new Date();
var re = /[^,]+/g
var source = re.test(str)?Array.prototype.slice.call(str.match(re),0,3): " ";
sr[sr.length] = [ "方法1: ",new Date()-ts, "ms ", " 结果: ",source].join( ' ');


//方法2
var ts = new Date();
var source = /^((?:[^,]*,){2}[^,]*)/.test(str)?RegExp.$1: " ";
sr[sr.length] = [ "方法2: ",new Date()-ts, "ms ", " 结果: ",source].join( ' ');

//方法3
var ts = new Date();
var source = str.split( ', ').slice(0,3);
sr[sr.length] = [ "方法3: ",new Date()-ts, "ms ", " 结果: ",source].join( ' ');

alert(sr.join( '\n '));

很明显直接用正则找前3个是最快的
------解决方案--------------------
var str = "123,234,345,456,567,678 "
alert(str.split(/\,/,3).join( ", "));
我喜欢这个.