Estoy tratando de reemplazar la siguiente cadena
\section{Welcome to $\mathbb{R}^n$} Some contentcon
<h1>Welcome to $\mathbb{R}^n$</h1> Some content Obviamente, el problema es que tengo aperturas { y } entre las llaves. He intentado usar algo como
strOutput = strOutput.replace(/\\section\*\s*\{([^}]*)\}/g, "<h1>$1</h1>");en JavaScript, pero sin suerte. ¿Cómo sigo acercándome a esto?
Aquí hay un ejemplo:
let str = String.raw`\section{Welcome to $\mathbb{R}^n$}` let result = `<h1>${str.match(/(?<={).*(?=})/)}</h1>` console.log(result)Qué tal esto:
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) El problema con su expresión era \* , lo que significa asteriscos literales, ¡pero por lo demás casi lo tiene!
Para el caso de uso del OP de llaves anidadas y no anidadas, se necesita una expresión regular que apunte y capture explícitamente el contenido entre dos llaves (apertura/cierre) que también contiene un par de llaves de apertura/cierre... /\{(?<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>`) )