Javascript 正则表达式:在正则表达式中搜索相同的值
我有这个字符串:Javascript 正则表达式:在正则表达式中搜索相同的值,javascript,regex,Javascript,Regex,我有这个字符串: const test = ` /** * @test * { * } * @example * { * "name": "Error", * } * @test * { * } * @example * { * "name": "Success", * } */ `; 我想返回字符串中找到的所有@example。 这是我的密码: const regexExample = /@example[\s\S]*?(?=@test|$)/g;
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
您的正则表达式是否良好,只需将其与一起使用即可一次性获得所有匹配项:
const测试=`
/**
*@测试
* {
* }
*@example
* {
*“名称”:“错误”,
* }
*@测试
* {
* }
*@example
* {
*“名称”:“成功”,
* }
*/
`;
常量匹配=test.match(/@example[\s\s]*?(?=@test |$)/g);
matches.forEach(m=>console.log(m))代码>@DoğancanArabacı我也在做同样的事情,但事实并非如此working@DoğancanArabacı我正在使用循环作为well@brxnzaz写入预期结果为什么返回在循环中?。删除它,这应该工作。