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

如何使用regex正则表达式提取字符串中首个括号内的内容

使用正则提取字符串中第一个括号内的内容

需求说明

存在包含多处括号包裹内容的字符串,仅需要提取第一个括号内的文本内容,示例字符串如下:
const str = "I (want to get this value), not this (value here)";

实现代码

const str = "I (want to get this value), not this (value here)";
// 匹配第一个英文括号内的内容
const result = str.match(/\((.*?)\)/)
const targetContent = result ? result[1] : ''
// 打印输出结果为:want to get this value
console.log(targetContent)

正则逻辑说明

  • \(:转义匹配字面量左括号(,括号属于正则特殊字符,必须转义才能匹配字符本身
  • (.*?):捕获组使用非贪婪匹配模式,匹配到第一个右括号就停止,避免匹配到后续括号的内容
  • \):转义匹配字面量右括号)

扩展说明

如果需要匹配中文全角括号,将正则替换为/((.*?))/即可。

内容的提问来源于stack exchange,提问作者God of all wars

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 14:57:02