Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

136
Visualizações
Regex replacing between brackets that contain the same type of bracket in between

I am trying to replace the following string

\section{Welcome to $\mathbb{R}^n$}
Some content

with

<h1>Welcome to $\mathbb{R}^n$</h1>
Some content

Obviously, the problem is that I have opening { and } between the curly brackets themselves. I have tried to use something like

strOutput = strOutput.replace(/\\section\*\s*\{([^}]*)\}/g, "<h1>$1</h1>");

in JavaScript, but with no luck. How do I go on approaching this?

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Here is an example:

let str = String.raw`\section{Welcome to $\mathbb{R}^n$}`

let result = `<h1>${str.match(/(?<={).*(?=})/)}</h1>`

console.log(result)

about 4 years ago · Juan Pablo Isaza Relatório

0

How about this:

let str = String.raw`\section{Welcome to $\mathbb{R}^n$}`
let m = str.replace(/\\section\s*\{(.*)}$/g, "$1")
let result = `<h1>${m}</h1>`

console.log(result)

The problem with your expression was \*, which means a literal asterisks, but otherwise you nearly had it!

about 4 years ago · Juan Pablo Isaza Relatório

0

For the OP's use case of nested and un-nested curly braces one needs a regex which explicitly targets and captures the content in between two braces (opening/closing) which also contains a pair of opening/closing braces ... /\{(?<nested>[^{}]+\{[^{}]+\}[^{}]+)\}/g ...

const sample = String.raw`\section{Welcome to $\mathbb{R}^n$} \textbf{Other text} \textbf{Other text}  \textbf{Other text} \textbf{Other text} \section{Welcome to $\mathbb{R}^n$}  \textbf{Other text}\section{Welcome to $\mathbb{R}^n$} \textbf{Other text} \textbf{Other text}  \textbf{Other text} \textbf{Other text} \section{Welcome to $\mathbb{R}^n$}  \textbf{Other text}`;

// see ... [https://regex101.com/r/z4hZUt/1/]
const regXNested = /\{(?<nested>[^{}]+\{[^{}]+\}[^{}]+)\}/g;

console.log(
  sample
    .replace(regXNested, (match, nested) => `<h1>${ nested }</h1>`)
)

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda