const regex = /(?(DEFINE) # Definitions
(?<needle>\\dfrac(?=[^\}]*\})) # What to search for
(?<skip>^[^\{]*\{|\}[^\{]*\{) # What we should skip
)
(?&skip)(*SKIP)(*FAIL) # Skip it
|
(?&needle) # Match it/gm;
// Alternative syntax using RegExp constructor
// const regex = new RegExp('(?(DEFINE) # Definitions
(?<needle>\\\\dfrac(?=[^\\}]*\\})) # What to search for
(?<skip>^[^\\{]*\\{|\\}[^\\{]*\\{) # What we should skip
)
(?&skip)(*SKIP)(*FAIL) # Skip it
|
(?&needle) # Match it', 'gm')
const str = `Démontrer par récurrence que pour tout entier naturel n,
\\dfrac
\\(\\displaystyle{1^2+2^2+\\ldots+n^2=\\sum_{k=0\\dfrac dsdq ds}rr^{n}k^2=\\dfrac{n(n+1)(2n+1)}{6}}\\)
Démontrer par récurrence que pour tout entier naturel n,
\\(\\displaystyle{1^2+2^2+\\ldots+n^2=\\sum_{k=0\\dfrac{test} fdfd}^{n}k^2=\\dfrac{n(n+1)(2n+1)}{6}}\\)
\\dfrac`;
const subst = `\\frac`;
// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);
console.log('Substitution result: ', result);
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for JavaScript, please visit: https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions