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

如何用正则表达式移除花括号及周边内容并保留括号内文本?

解决方案

要移除\name{...}这类结构中的命令部分与花括号,仅保留括号内的内容,用正则表达式替换就能高效实现需求。

Python 实现

import re

test_string = "Hello my name is \\name{John} \\name{Doe}"
processed_string = re.sub(r'\\name\{(.*?)\}', r'\1', test_string)
print(processed_string)  # 输出: Hello my name is John Doe

JavaScript 实现

const testString = "Hello my name is \\name{John} \\name{Doe}";
const processedString = testString.replace(/\\name\{(.*?)\}/g, "$1");
console.log(processedString); // 输出: Hello my name is John Doe

正则表达式说明

  • \\name\{:匹配固定前缀\name{(反斜杠和花括号属于正则特殊字符,需额外加反斜杠转义)
  • (.*?):非贪婪捕获括号内的任意内容,确保只匹配到最近的闭合花括号,避免过度匹配
  • \}:匹配闭合花括号
  • 替换时用\1(Python)或$1(JavaScript)引用捕获到的括号内文本,直接替换掉整个\name{...}结构

扩展场景

如果需要处理所有类似\xxx{...}的命令结构(比如\age{30}、\city{New York}),可以把正则调整为:

# Python 扩展版
processed_string = re.sub(r'\\\w+\{(.*?)\}', r'\1', test_string)
// JavaScript 扩展版
const processedString = testString.replace(/\\\w+\{(.*?)\}/g, "$1");

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 11:11:08