正则表达式替换括号之间包含相同类型的括号
Regex replacing between brackets that contain the same type of bracket in between
我正在尝试替换以下字符串
\section{Welcome to $\mathbb{R}^n$}
Some content
和
<h1>Welcome to $\mathbb{R}^n$</h1>
Some content
显然,问题是我在大括号本身之间打开了 {
和 }
。我试过使用类似
的东西
strOutput = strOutput.replace(/\section\*\s*\{([^}]*)\}/g, "<h1></h1>");
在 JavaScript 中,但没有运气。我该如何继续解决这个问题?
这是一个例子:
let str = String.raw`\section{Welcome to $\mathbb{R}^n$}`
let result = `<h1>${str.match(/(?<={).*(?=})/)}</h1>`
console.log(result)
这个怎么样:
let str = String.raw`\section{Welcome to $\mathbb{R}^n$}`
let m = str.replace(/\section\s*\{(.*)}$/g, "")
let result = `<h1>${m}</h1>`
console.log(result)
你的表达方式有问题 \*
,意思是字面上的星号,但除此之外你差一点就成功了!
对于 OP 的嵌套和非嵌套大括号用例,需要一个正则表达式,它明确定位并捕获两个大括号 (opening/closing) 之间的内容,其中还包含一对 opening/closing 大括号 ... /\{(?<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>`)
)
我正在尝试替换以下字符串
\section{Welcome to $\mathbb{R}^n$}
Some content
和
<h1>Welcome to $\mathbb{R}^n$</h1>
Some content
显然,问题是我在大括号本身之间打开了 {
和 }
。我试过使用类似
strOutput = strOutput.replace(/\section\*\s*\{([^}]*)\}/g, "<h1></h1>");
在 JavaScript 中,但没有运气。我该如何继续解决这个问题?
这是一个例子:
let str = String.raw`\section{Welcome to $\mathbb{R}^n$}`
let result = `<h1>${str.match(/(?<={).*(?=})/)}</h1>`
console.log(result)
这个怎么样:
let str = String.raw`\section{Welcome to $\mathbb{R}^n$}`
let m = str.replace(/\section\s*\{(.*)}$/g, "")
let result = `<h1>${m}</h1>`
console.log(result)
你的表达方式有问题 \*
,意思是字面上的星号,但除此之外你差一点就成功了!
对于 OP 的嵌套和非嵌套大括号用例,需要一个正则表达式,它明确定位并捕获两个大括号 (opening/closing) 之间的内容,其中还包含一对 opening/closing 大括号 ... /\{(?<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>`)
)