JavaScript 通过多次出现的字母拆分字符串 [英] JavaScript Split string by multiple occurrences of letters
问题描述
我正在尝试用单个或多个字母分割字符串.
I am trying to split a string by a single or multiple occurrence of letters.
例如:
aaabbcapppp
,将产生数组,["aaa", "bb", "c", "a", "pppp"]
我最低效的想法是利用 newArray = str.split("");
并根据我的需要重建数组.我认为有一个更有效的解决方案.
The most-Inefficient idea I had was to just utilize, newArray = str.split("");
and rebuild the array to my needs. I assume there is a much more efficient solution.
推荐答案
这样的事情会起作用:
"aaabbcapppp".match(/(.)1*/g) // ["aaa", "bb", "c", "a", "pppp"]
(.)
匹配第 1 组中捕获的任何单个字符,后跟重复零次或多次的相同字符(1
是一个反向引用,它完全匹配第 1 组中匹配的内容).
The (.)
matches any single character, captured in group 1, followed by that same character repeated zero or more times (1
is a backreference which matches exactly what was matched in group 1).
要仅匹配拉丁字母,请考虑使用 [a-z]
,例如:
To match only Latin letters, consider using [a-z]
, for example:
"aaa-bbca!!pppp".match(/([a-z])1*/g) // ["aaa", "bb", "c", "a", "pppp"]
这里,-
和 !!
不包含在结果数组中.
Here, the -
and !!
are not included in the result array.
这篇关于JavaScript 通过多次出现的字母拆分字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!