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

如何使用C#提取字符串中括号间的所有内容?

提取字符串中所有括号内内容的最优方案

嗨,这个问题我之前处理字符串的时候也碰到过!你现在只能拿到第一个括号里的内容,大概率是因为用了单次匹配的方法——想要一次性提取所有括号内的内容,正则表达式的全局非贪婪匹配就是最通用的解决方案。

核心思路

我们需要匹配所有被(和)包裹的内容,关键是用非贪婪模式(避免把多个括号之间的内容连起来匹配),同时开启全局匹配,这样就能捕获到所有符合条件的内容。

代码示例(Python)

这是最常用的实现,re.findall()会直接返回所有匹配的结果:

import re

input_text = "You id is (1) and your number is (0000000000)"
# 正则解释:\(匹配左括号,(.*?)非贪婪捕获括号内任意内容,\)匹配右括号
captured_content = re.findall(r'\((.*?)\)', input_text)
print(captured_content)  # 输出: ['1', '0000000000']

代码示例(JavaScript)

如果是前端场景,有两种常用写法:

  1. 先全局匹配带括号的内容,再截取掉括号:
const inputText = "You id is (1) and your number is (0000000000)";
const fullMatches = inputText.match(/\((.*?)\)/g) || [];
const capturedContent = fullMatches.map(item => item.slice(1, -1));
console.log(capturedContent); // 输出: ['1', '0000000000']
  1. 用exec()循环捕获(适合需要处理更复杂匹配逻辑的场景):
const inputText = "You id is (1) and your number is (0000000000)";
const regex = /\((.*?)\)/g;
let match;
const capturedContent = [];
while ((match = regex.exec(inputText)) !== null) {
  capturedContent.push(match[1]);
}
console.log(capturedContent); // 输出: ['1', '0000000000']

注意事项

  • 如果你的字符串里有嵌套括号(比如(a(b)c)),上面的基础正则会提取到a(b,因为它只会匹配到第一个右括号。这种场景需要用支持递归的正则库(比如Python的第三方regex库),或者手动处理嵌套逻辑。
  • 确保括号是成对出现的,否则可能会出现匹配不完整的情况。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 10:08:10