如何从API返回的字符串中提取反引号包裹的代码块子串
提取字符串中所有三个反引号包裹的代码块
核心解决方案:使用带全局标志的非贪婪正则表达式
用/```([\s\S]*?)```/g这个正则可以精准匹配所有被三个反引号包裹的代码块,不管是单个还是多个都能正确提取。
正则表达式说明
```:匹配开头的三个反引号分隔符([\s\S]*?):非贪婪捕获组,[\s\S]匹配任意字符(包括换行),*?确保匹配到最近的结尾反引号就停止,避免过度匹配g:全局匹配标志,会遍历整个字符串找出所有符合规则的代码块
单个代码块提取示例
const originalString = 'this is some string and I want to extract ```the code contained in the backticks```'; const regex = /```([\s\S]*?)```/; const matchResult = originalString.match(regex); const extractedCode = matchResult ? matchResult[1] : ''; console.log(extractedCode); // 输出: the code contained in the backticks
多个代码块提取示例
如果字符串包含多个代码块,用循环遍历匹配结果:
const multiBlockStr = 'intro text ```function foo() {}``` middle content ```const bar = "test"``` end text'; const regex = /```([\s\S]*?)```/g; const allCodeBlocks = []; let currentMatch; // 遍历所有匹配项 while ((currentMatch = regex.exec(multiBlockStr)) !== null) { allCodeBlocks.push(currentMatch[1]); } console.log(allCodeBlocks); // 输出: ["function foo() {}", "const bar = \"test\""]
为什么之前的方法失效
- 用
substring结合indexOf/lastIndexOf的方式,只能定位第一个开头反引号和最后一个结尾反引号,当存在多个代码块时,会把中间的普通文本也包含进去,无法精准拆分每个代码块。 - 如果正则不用非贪婪模式(把
*?写成*),会直接从第一个开头反引号匹配到最后一个结尾反引号,同样会导致过度匹配。
内容的提问来源于stack exchange,提问作者jpyrz
相关产品推荐
相关产品推荐

