togrultopal
togrultopal

Reputation: 111

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?

Upvotes: 0

Views: 125

Answers (3)

Peter Seliger
Peter Seliger

Reputation: 13432

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>`)
)

Upvotes: 0

Timur
Timur

Reputation: 2287

Here is an example:

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

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

console.log(result)

Upvotes: 1

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!

Upvotes: 0

Related Questions