正则表达式匹配以 // 开头的连续行
可以使用如下正则表达式匹配以 '//' 开头的连续行:
/^//.*$/gm
其中:
- '^' 表示匹配字符串的开头;
- '//' 匹配两个连续的斜杠;
- '.*' 匹配任意字符,重复任意次数;
- '$' 表示匹配字符串的结尾;
- 'g' 表示全局匹配,即匹配所有符合条件的结果;
- 'm' 表示多行匹配,即将字符串视为多行,使 '^' 和 '$' 可以匹配每一行的开头和结尾。
示例:
const str = '// This is a comment.
// This is another comment.
Not a comment.';
const regex = /^//.*$/gm;
const matches = str.match(regex);
console.log(matches);
// Output: ['// This is a comment.', '// This is another comment.']
解释:
- 第一行和第二行都以 '//' 开头,并且后面还有其他字符,符合正则表达式的条件;
- 第三行不以 '//' 开头,不符合正则表达式的条件。
原文地址: https://www.cveoy.top/t/topic/ogUh 著作权归作者所有。请勿转载和采集!