2013-03-12 63 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));