工作代码笔(包括更多的块注释等):
https://codepen.io/Frederic-Klein/pen/KbXxeB?editors=0012
用于使用正则表达式匹配和替换给定示例的示例代码
(...)
和非捕获
(?:...)
const content = `
/* api_start ====
app.use('/api',require('./api/api'));
app.use('/sms',require('./api/sms'));
==== api_end */
// app.use('/api',require('./api/api'));
// app.use('/sms',require('./api/sms'));
`;
const regex_block_comments = /^\/\*.*\n((?:app.*\n)*)(?:.*\*\/\n)/gm;
// match lines
// starting with /*
// having the following lines start with app, capture all those lines as one group ($1 reference)
// having a line ending with */ afterwards, as non-capturing group
// repeat globally (g) and match multiline (m) string
const regex_comment = /^\/\/\s*(app.*;\n)/gm;
// match lines
// starting with //
// ignore following whitespaces
// having text "app" afterwards, capture from app to line-ending as group ($1 reference)
const replacement = `$1`;
newcontent = content.replace(regex_block_comments,replacement);
newcontent = newcontent.replace( regex_comment,replacement);
// content after replacements
console.log(newcontent);
要了解更多关于正则表达式和构建模式的信息,我建议
https://regexr.com/
https://regex101.com/
.