JavaScript正则表达式分割数字和字母

时间:2021-08-25 19:28:59

I need regex pattern to split a string into numbers and letters. I.e. .1abc2.5efg3mno should be split into [".1","abc","2.5","efg","3","mno"].

我需要正则表达式模式将字符串拆分为数字和字母。即.1abc2.5efg3mno应分为[“。1”,“abc”,“2.5”,“efg”,“3”,“mno”]。

The current regex I tried is:

我试过的当前正则表达式是:

var str = ".1abc2.5efg3mno";
regexStr= str.match(/[a-zA-Z]+|[0-9]+(?:\.[0-9]+|)/g);

Output obtained is:

获得的输出是:

["1","abc","2.5","efg","3","mno"]

The number .1 is taken as 1 whereas I need it as .1.

数字.1被视为1而我需要它为.1。

1 个解决方案

#1


10  

If it's a matter of separating letters from non-letters, then the regex can be made quite simple:

如果是将字母与非字母分开,则可以使正则表达式变得非常简单:

var str = ".1abc2.5efg3mno";
var regexStr = str.match(/[a-z]+|[^a-z]+/gi);
console.log(regexStr);

I.e. match a group of letters or a group of non-letters.

即匹配一组字母或一组非字母。

#1


10  

If it's a matter of separating letters from non-letters, then the regex can be made quite simple:

如果是将字母与非字母分开,则可以使正则表达式变得非常简单:

var str = ".1abc2.5efg3mno";
var regexStr = str.match(/[a-z]+|[^a-z]+/gi);
console.log(regexStr);

I.e. match a group of letters or a group of non-letters.

即匹配一组字母或一组非字母。