Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

135
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!