【问题标题】:Regex: Search in regex for the same value [duplicate]正则表达式:在正则表达式中搜索相同的值 [重复]
【发布时间】:2019-08-12 11:40:33
【问题描述】:

我有这个字符串:

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

【问题讨论】:

  • @DoğancanArabacı 我也在做同样的事情,但它不起作用
  • @DoğancanArabacı 我也在使用循环
  • @brxnzaz 写出预期的结果
  • 你为什么要return在循环中?删除它,这应该可以工作。

标签: javascript regex


【解决方案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));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-02
    • 2023-04-10
    • 2013-08-16
    相关资源
    最近更新 更多