You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用正则匹配含注释大括号的TypeScript单个接口?

解决TypeScript接口匹配正则问题

问题分析

你之前尝试的正则无法正常工作的核心原因:

  • /export interface .*\{([^}])+\}/g:用[^}]匹配非右大括号字符,遇到注释里的}就会提前终止匹配,无法获取完整接口体
  • /export interface .*\{([^])+\}/g:[^]匹配任意字符(包括换行),会从第一个接口开头一直匹配到最后一个接口结尾,把中间的注释和无关内容全部包含进去

解决方案

使用支持递归匹配的正则表达式,它能正确忽略注释内的大括号,精准匹配单个完整接口:

/export interface \w+\s*\{(?:(?:\/\*[\s\S]*?\*\/)|(?:\/\/[^\n]*\n)|[^{}]|(?R))*\}/g

正则结构解析

  • export interface \w+\s*\{:匹配接口的起始部分,包含export interface关键字、接口名和紧跟的左大括号
  • 内部非捕获组(?: ... )*循环匹配接口体内容,覆盖四种场景:
    • \/\*[\s\S]*?\*\/:匹配多行文档注释/** ... */,[\s\S]兼容换行,*?非贪婪匹配避免过度捕获
    • \/\/[^\n]*\n:匹配单行注释// ...,直到换行结束
    • [^{}]:匹配既不是左大括号也不是右大括号的普通字符
    • (?R):递归匹配整个正则,处理接口内嵌套的大括号(比如嵌套对象类型)

使用示例

在TypeScript/JavaScript环境中测试:

const code = `export interface SomeInterface {
  /**
   * Some comment on property1
   */
  property1: string;
  /**
   * Some comment on property2, including RegEx pattern with curly braces such as [a-z1-9]{2}
   */
  property2: string;
  /**
   * Some comment on property3
   */
  property3: string;

  // some more properties and doc comments, some of which have curly braces inside too
}

// This comment has to be excluded

export interface AnotherInterface {
  // internally very similar to 'SomeInterface' above
}`;

const regex = /export interface \w+\s*\{(?:(?:\/\*[\s\S]*?\*\/)|(?:\/\/[^\n]*\n)|[^{}]|(?R))*\}/g;
const matchedInterfaces = code.match(regex);
// matchedInterfaces数组会包含两个元素,分别对应两个完整的接口定义

注意事项

  • 该正则依赖ES2018及以上的正则特性(递归匹配(?R)),现代浏览器和Node.js环境均支持
  • 假设接口定义格式规范,没有异常的大括号嵌套或语法错误

内容的提问来源于stack exchange,提问作者gretarsson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 10:52:54