Skip to content

Instantly share code, notes, and snippets.

@kindy
Created July 17, 2018 10:12
Show Gist options
  • Save kindy/4bda185d58d50dd6e7e845a5d7db83a0 to your computer and use it in GitHub Desktop.
Save kindy/4bda185d58d50dd6e7e845a5d7db83a0 to your computer and use it in GitHub Desktop.
文本正则替换 模式
// 此处所列函数只是框架,实际使用仍需要调整和修正
// 提供的是一个思路
// 替换函数是同步的
function replSync(txt) {
let pick = (s, e) => txt.substring(s, e);
const re = /\w/g;
const buf = [];
let lastIdx = 0;
let m;
while ((m = re.exec(txt)) !== null) {
const {[0]: m0, index: idx} = m;
if (idx !== lastIdx) {
buf.push(pick(lastIdx, idx));
}
buf.push('new txt');
lastIdx = idx + m0.length;
}
if (lastIdx < txt.length) {
buf.push(pick(lastIdx, txt.length));
}
return buf.join('');
}
// 替换函数是异步的
async function replAsync(txt, processMatch) {
let matches = [];
const fill = (m, pre, con, suf, offset) => {
matches.push({
range: [offset + pre.length, offset + m.length - suf.length],
m,
pre, suf,
});
};
let re = /\b(['"])(.+?)(\2)/g;
txt.replace(re, fill);
if (!matches.length) {
return txt;
}
const errors = [];
await Promise.all(matches.map((m) => {
return new Promise((resolve, reject) => {
processMatch(m, (err, ret) => {
if (err) {
errors.push({m, err});
} else {
m.ret = ret;
}
resolve();
});
});
}));
if (errors.length) {
let err = new Error();
err.errors = errors;
throw err;
}
let buf = [];
matches.forEach((m, idx) => {
buf.push(
s.substring(
idx === 0 ? 0 : matches[idx - 1].range[1],
m.range[0]
)
);
buf.push(m.ret);
});
buf.push(
s.substring(
matches[matches.length - 1].range[1],
s.length
)
);
return buf.join('');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment