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

时间:2023-02-02 21:37:43

Using Regex how can I split a string based on number occurrence?

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

For example I have a string like below.

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

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

I need to split it like,

我需要把它分开,就像

Expected Output:

1 dozen   
3 dozen   
4 dozen kg

I tried the following regex,

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

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

but end up with

但结束了

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

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

Please help me on framing the regex and feel free to ask if my question is not clear.

请帮我构建正则表达式,并随时询问我的问题是否不清楚。

fiddle

2 个解决方案

#1


3  

This positive lookahead based split call can do the job:

这种积极的前瞻性拆分调用可以完成这项工作:

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

will give:

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

Explanation: Breaking down this regex /\s*(?=\d+)/

说明:分解这个正则表达式/ \ 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+) is actually a positive lookahead.

PS :(?= \ d +)实际上是一个积极的前瞻。

#2


5  

Why don't you use 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  

This positive lookahead based split call can do the job:

这种积极的前瞻性拆分调用可以完成这项工作:

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

will give:

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

Explanation: Breaking down this regex /\s*(?=\d+)/

说明:分解这个正则表达式/ \ 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+) is actually a positive lookahead.

PS :(?= \ d +)实际上是一个积极的前瞻。

#2


5  

Why don't you use 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"]