3

使用正则表达式如何根据数字出现拆分字符串?

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

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如果我的问题不清楚,请随时询问。

小提琴

4

2 回答 2

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"]
于 2013-08-03T07:55:00.333 回答
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+)其实是一个积极的lookahead

于 2013-08-03T07:56:17.820 回答