2013-03-12 60 views
1

我有以下輸入:正則表達式填充字符串

123456_r.xyz 
12345_32423_131.xyz 
1235.xyz 
237213_21_mmm.xyz 

現在我需要在第一次連接數字填補到8位數字與0領先:

0_r.xyz 
00_32423_131.xyz 
000.xyz 
00237213_21_mmm.xyz 

我的嘗試是分割點,然後分割(如果存在)下劃線,並獲得第一個數字並填充它們。

但我認爲會有一個更有效的方式與正則表達式替換功能只有一個功能,對不對?這看起來如何?

TIA 馬特

+1

我不認爲有這樣做的正則表達式,並且這樣做的js代碼非常短。 – 2013-03-12 08:30:39

回答

4

我會使用一個正則表達式,但只是針對劈裂:

var input = "12345_32423_131.xyz"; 
var output = "00000000".slice(input.split(/_|\./)[0].length)+input; 

結果:"00_32423_131.xyz"

編輯:

快,NO-分裂但沒有正則表達式,我在評論中給出的解決方案:

"00000000".slice(Math.min(input.indexOf('_'), input.indexOf('.'))+1)+input 
+0

如果你想要一個優化版本,用indexOf('_')'和'indexOf('。')'的最小值來代替分割。但後來我的回答沒有正則表達式... – 2013-03-12 08:37:44

+0

它的工作原理,但你可以解釋這是什麼:'split(/ _ | \ ./)'? TIA – frgtv10 2013-03-12 09:09:48

+0

它用'_'或'.'分隔字符串作爲分隔符,以獲得第一個整數的長度。這是最簡潔的,但如果你真的需要最快的解決方案,使用'「00000000」.slice(Math.min(input.indexOf('_'),input.indexOf('。'))+ 1)+ input; – 2013-03-12 09:11:48

2

我不會拆可言,只需更換:

"123456_r.xyz\n12345_32423_131.xyz\n1235.xyz\n237213_21_mmm.xyz".replace(/^[0-9]+/mg, function(a) {return '00000000'.slice(0, 8-a.length)+a}) 
+0

不知道替換或從@dystroy的版本更好:) – frgtv10 2013-03-12 09:08:55

+0

這真的取決於如果你想獲得一個字符串作爲結果或字符串數​​組。我的方法更清潔我會說:) – WTK 2013-03-12 10:18:57

2

有一個簡單的正則表達式找到要替換字符串的一部分,但你需要使用a replace function執行你想要的行動。

// The array with your strings 
var strings = [ 
    '123456_r.xyz', 
    '12345_32423_131.xyz', 
    '1235.xyz', 
    '237213_21_mmm.xyz' 
]; 

// A function that takes a string and a desired length 
function addLeadingZeros(string, desiredLength){ 
    // ...and, while the length of the string is less than desired.. 
    while(string.length < desiredLength){ 
     // ...replaces is it with '0' plus itself 
     string = '0' + string; 
    } 

    // And returns that string 
    return string; 
} 

// So for each items in 'strings'... 
for(var i = 0; i < strings.length; ++i){ 
    // ...replace any instance of the regex (1 or more (+) integers (\d) at the start (^))... 
    strings[i] = strings[i].replace(/^\d+/, function replace(capturedIntegers){ 
     // ...with the function defined above, specifying 8 as our desired length. 
     return addLeadingZeros(capturedIntegers, 8); 
    }); 
}; 

// Output to screen! 
document.write(JSON.toString(strings));