如何使用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
相关产品推荐
相关产品推荐

