【问题标题】:Regex to match keywords inside specific context正则表达式匹配特定上下文中的关键字
【发布时间】:2018-03-13 15:55:24
【问题描述】:

我是正则表达式的新手。基本上,我想匹配“private”的所有实例,但前提是它们出现在构造函数的参数列表中。

这是我的示例文本:

constructor(
  private optionsService: OptionsService,
  private modalService: BsModalService,
  private renderer: Renderer2,
  private messageService: MessageService,
  private queryBuilderService: QueryBuilderService,
  private ltPlacementService: LtPlacementService,
  private sanitizer: DomSanitizer
) { } // All of the above should match

private someOtherVariable; // Should not match

有没有办法匹配 constructor(...) { } 中的所有内容,然后仅在这个结果中匹配“private”的实例?提前致谢。

【问题讨论】:

    标签: javascript regex typescript


    【解决方案1】:

    要从constructor( 匹配到) {,您可以使用constructor\(([\s\S]+(?=\)\s*{)),然后在捕获组(组1)中捕获中间的文本。

    这将匹配

    • constructor 字面匹配
    • \(匹配(
    • (抓包组(组1)
      • [\s\S]+ 匹配任何空白或非空白字符
      • (?= 肯定的前瞻,断言接下来的内容
        • \)\s*{ Match )、零个或多个空格和 {
      • )关闭正向预测
    • )关闭捕获组

    然后从第1组的文本中匹配private

    \bprivate\b

    例如:

    let string = `constructor(
      private optionsService: OptionsService,
      private modalService: BsModalService,
      private renderer: Renderer2,
      private messageService: MessageService,
      private queryBuilderService: QueryBuilderService,
      private ltPlacementService: LtPlacementService,
      private sanitizer: DomSanitizer
    ) { } // All of the above should match
    
    private someOtherVariable; // Should not match`;
    
    const pattern = /constructor\(([\s\S]+(?=\)\s*{))/g;
    pattern.exec(string)[1].match(/\bprivate\b/g).forEach((p) => {
      console.log(p);
    });

    【讨论】:

    • 感谢您的回答。我最终使用 AWK 实现了我的目标,但我相信这对另一个心烦意乱的程序员会很有帮助。标记为已接受。干杯:)
    猜你喜欢
    • 2020-07-01
    • 1970-01-01
    • 2017-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-01
    • 1970-01-01
    相关资源
    最近更新 更多