簡體   English   中英

JavaScript通過正則表達式拆分字符串

[英]JavaScript split string by regex

我將有一個長度不超過8個字符的字符串,例如:

// represented as array to demonstrate multiple examples
var strs = [
    '11111111',
    '1RBN4',
    '12B5'
]    

在瀏覽函數時,我希望將所有數字字符相加以返回最終字符串:

var strsAfterFunction = [
    '8',
    '1RBN4',
    '3B5'
]

你可以看到第一個字符串中的所有8個單個1字符最終都是一個8字符的字符串,第二個字符串保持不變,因為沒有相鄰的數字字符,第三個字符串隨着12字符變為a 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

什么是.split正則表達式由多個adajcent數字字符分割,例如:

var str = '12RB1N1'
  => ['12', 'R', 'B', '1', 'N', '1']

編輯:

問題:如果結果為“27”或“9”,字符串“999”怎么樣?

如果很明顯,總是SUM數字, 999 => 27234 => 9

你可以為整個轉型做到這一點:

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

對於您的strs數組,它返回["8", "1RBN4", "3B5"]

var results = string.match(/(\d+|\D+)/g);

測試:

"aoueoe34243euouoe34432euooue34243".match(/(\d+|\D+)/g)

返回

["aoueoe", "34243", "euouoe", "34432", "euooue", "34243"]

喬治......我的答案最初類似於dystroy's,但是當我今晚回到家並找到你的評論后,我無法挑戰

:)

這里沒有正則表達式。 fwiw它可能更快,它將是一個有趣的基准,因為迭代是原生的。

function p(s){
  var str = "", num = 0;
  s.split("").forEach(function(v){
    if(!isNaN(v)){
        (num = (num||0) + +v);
    } else if(num!==undefined){
        (str += num + v,num = undefined);
    } else {
        str += v;
    }
  });
  return str+(num||"");
};

// TESTING
console.log(p("345abc567"));
// 12abc18
console.log(p("35abc2134mb1234mnbmn-135"));
// 8abc10mb10mnbmn-9
console.log(p("1 d0n't kn0w wh@t 3153 t0 thr0w @t th15 th1n6"));
// 1d0n't0kn0w0wh@t12t0thr0w0@t0th6th1n6

// EXTRY CREDIT
function fn(s){
    var a = p(s);
    return a === s ? a : fn(a);
}

console.log(fn("9599999gh999999999999999h999999999999345"));
// 5gh9h3

這里是小提琴和一個新的小提琴,沒有過於聰明的三元組

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM