根据任何数字出现拆分字符串

时间:2013-08-03 07:52:02

标签: javascript regex

使用Regex如何根据出现次数拆分字符串?

例如,我有一个如下所示的字符串。

var text = "1 dozen 3 dozen 4 dozen kg";

我需要拆分它,

预期输出:

1 dozen   
3 dozen   
4 dozen kg

我尝试了以下正则表达式,

var text = "1 dozen 3 dozen 4 dozen kg";
var regex = /(\d\s)/g;  // regex I tried
console.log(text.split(regex));

但最终以

结束
  

[“”,“1”,“打”,“3”,“打”,“4”,“打公斤”]

请帮助我构建regex,并随时询问我的问题是否不明确。

fiddle

2 个答案:

答案 0 :(得分:5)

为什么不使用match

var text = "1 dozen 3 dozen 4 dozen kg";
var regex = /\d\s\D+/g;
console.log(text.match(regex)); //=> ["1 dozen ", "3 dozen ", "4 dozen kg"]

答案 1 :(得分:3)

这个基于positive lookahead的拆分调用可以完成这项工作:

var arr = text.split(/\s*(?=\d+)/);

会给:

["1 dozen", "3 dozen", "4 dozen kg"]

说明:打破此正则表达式/\s*(?=\d+)/

\s*        - match 0 or more spaces
(?=\d+)    - Make sure previous match is immediately followed by 1 or more digits
\s*(?=\d+) - match 0 or more spaces if it is immediately followed by 1 or more digits

PS:(?=\d+)实际上是positive lookahead