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屋!