一个“A2B3”这样的字符串,输出“AABBB”

应该是写正则表达式,但是我实在写不出来

阅读 8.6k
9 个回答
var str = 'A2B3';
var beforeOffset=0;
str.replace(/\d*/g,function(match, offset, string){
   var padStr =string.slice(beforeOffset, offset);
   beforeOffset = offset;
   return ''.padEnd(match-1, padStr);
})
"AABBB"
'A2B3'.replace(/(([a-zA-Z]+)(\d+))/g, (match, content, char, repeat) => String(char).repeat(repeat))
'A2B3'.replace(/([A-z]+)(\d+)/g, (_, $1, $2) => $1.repeat($2))
function repeat(string) {
    let result = "";
    let count = 0;
    let letter = "";
    let repeatString = "";
    let numbers = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"];
    while (count < string.length) {
        if (!numbers.includes(string[count])) {
            if (repeatString !== "") {
                result += letter.repeat(repeatString);
                repeatString = "";
                letter = string[count];
            } else {
                letter += string[count];
                if (count === string.length - 1) {
                    result += letter;
                }
            }
        } else {
            repeatString += string[count];
            if (count === string.length - 1) {
                result += letter.repeat(repeatString);
            }
        }
        count++;
    }

    return result;
}

可以尝试下根据 12345789 对字符串截取
拿到数字前的字母和数字
组合成一个类似这样的数组

[
  { label: 'A', num: 2 },
  { label: 'B', num: 3 }
]

然后根据num和label组成新的字符串

'A2B3'.replace(/(?<=[a-zA-Z]+)\d+/g,(num,index,str) => ''.padEnd(num-1,str[index-1]))
"A2B3".match(/[a-zA-Z]+\d+/g).map(_text=>_text.match(/[a-zA-Z]+/)[0].repeat(_text.match(/\d+/)[0])).join("")

进行了简单测试,有错误别说太狠

拿走不谢

var str = 'a2b3c12d123'
console.log(getMyString(str))

function getMyString(str) {
    var re = /[a-zA-Z](\d+)/g
    var list = str.match(re)
    var objList = list.map(item => {
        var 字母 = item.match(/[a-zA-Z]/)[0]
        var 数字 = item.match(/\d+/g)
        数字 = parseInt(数字)
        return {
            字母,
            数字
        }
    })
    var result = objList.map(obj => {
        return obj.字母.repeat(obj.数字)
    }).join('')
    return result
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏