分组
2023年08月10日
一、同类型后置
正则表达式: /\w{1,2}(?=(\w{2})+$)/g
function groupValue(value, index, flag) {
const reg = new RegExp(`\\w{1,${index}}(?=(\\w{${index}})+$)`, "g");
return String(value).replace(reg, function (match, ...args) {
return match + flag;
});
}
const str = "aabbccddeeffgge";
console.log(groupValue(str,2,",")); // a,ab,bc,cd,de,ef,fg,ge
二、同类型后置
方案二: /(\w{2}(?=\w))/g
function groupValue(value, index, flag) {
const reg = new RegExp(`(\\w{${index}}(?=\\w))`, "g");
return String(value).replace(reg, function (match, ...args) {
return match + flag;
});
}
const str = "aabbccddeeffgge";
console.log(groupValue(str,2,",")); // aa,bb,cc,dd,ee,ff,gg,e
三、数字运算符
function groupValue(value, flag) {
const reg =
/(((\d+)(\.\d+)?)(?=[\+\-\*\/\(\)])|([\+\-\*\/\(\)]{1})(?=[\d\+\-\*\/\(\)]))/g;
return String(value).replace(reg, function (match, ...args) {
return match + flag;
});
}
const str = "300.400*3.44-(3.44+4/2)";
console.log(groupValue(str,",").split(","));