1

我有以下输入:

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

现在我需要将第一个连接的数字填充为 8 个以 0 开头的数字:

00123456_r.xyz
00012345_32423_131.xyz
00001235.xyz
00237213_21_mmm.xyz

我的尝试是拆分一个点,然后在下划线拆分(如果存在)并获取第一个数字并填充它们。

但我认为只有一个函数的正则表达式替换函数会有一种更有效的方法,对吧?这会是什么样子?

TIA 马特

4

3 回答 3

4

我会使用正则表达式,但仅用于拆分:

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

结果 :"00012345_32423_131.xyz"

编辑 :

我在评论中给出的快速、不拆分但不使用正则表达式的解决方案:

"00000000".slice(Math.min(input.indexOf('_'), input.indexOf('.'))+1)+input
于 2013-03-12T08:35:05.710 回答
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})
于 2013-03-12T08:41:01.633 回答
2

有一个简单的正则表达式可以找到您想要替换的字符串部分,但您需要使用替换函数来执行您想要的操作。

// 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));
于 2013-03-12T08:44:14.930 回答