JavaScript通过正则表达式拆分字符串

Har*_*rry 5 javascript regex split

我将有一个长度不超过8个字符的字符串,例如:

// represented as array to demonstrate multiple examples
var strs = [
    '11111111',
    '1RBN4',
    '12B5'
]    
Run Code Online (Sandbox Code Playgroud)

在浏览函数时,我希望将所有数字字符相加以返回最终字符串:

var strsAfterFunction = [
    '8',
    '1RBN4',
    '3B5'
]
Run Code Online (Sandbox Code Playgroud)

在这里你可以看到所有的8个单1字符的第一个字符串中最终成为一个单一的8字符串,第二个字符串保持不变,因为在任何时候都存在相邻数字字符,第三串改变为12字符成为3其余字符串不变.

我认为在伪代码中执行此操作的最佳方法是:

1. split the array by regex to find multiple digit characters that are adjacent
2. if an item in the split array contains digits, add them together
3. join the split array items
Run Code Online (Sandbox Code Playgroud)

什么是.split由多个adajcent数字字符分割的正则表达式,例如:

var str = '12RB1N1'
  => ['12', 'R', 'B', '1', 'N', '1']
Run Code Online (Sandbox Code Playgroud)

编辑:

问题:如果结果为"27"或"9",字符串"999"怎么样?

如果清楚,总是将数字,999=> 27,234=>和9

Den*_*ret 12

你可以为整个转型做到这一点:

var results = strs.map(function(s){
    return s.replace(/\d+/g, function(n){
       return n.split('').reduce(function(s,i){ return +i+s }, 0)
    })
});
Run Code Online (Sandbox Code Playgroud)

对于您的strs数组,它返回["8", "1RBN4", "3B5"].


mze*_*ler 5

var results = string.match(/(\d+|\D+)/g);
Run Code Online (Sandbox Code Playgroud)

测试:

"aoueoe34243euouoe34432euooue34243".match(/(\d+|\D+)/g)
Run Code Online (Sandbox Code Playgroud)

返回

["aoueoe", "34243", "euouoe", "34432", "euooue", "34243"]
Run Code Online (Sandbox Code Playgroud)

  • ..但@dystroy充分利用它并为您提供了整个算法:) (2认同)