我有这个字符串:
const test = `
/**
* @test
* {
* }
* @example
* {
* "name": "Error",
* }
* @test
* {
* }
* @example
* {
* "name": "Success",
* }
*/
`;
我想返回字符串中找到的所有@example
。
这是我的代码:
const regexExample = /@example[\s\S]*?(?=@test|$)/g;
let m;
do {
m = regexExample.exec(test)
if (m) {
console.log(m[0]);
return m[0];
}
} while (m);
我得到的输出是:
@example
* {
* "name": "Error",
* }
*
如何搜索所有@example
,以及如何找到@
来验证其是否等同于@example
答案 0 :(得分:1)
您的正则表达式很好,只需将其与String.prototype.match()一起使用即可一次性获得所有匹配项:
const test = `
/**
* @test
* {
* }
* @example
* {
* "name": "Error",
* }
* @test
* {
* }
* @example
* {
* "name": "Success",
* }
*/
`;
const matches = test.match(/@example[\s\S]*?(?=@test|$)/g);
matches.forEach(m => console.log(m));