re = /(?(DEFINE) # Definitions
(?<needle>\\dfrac(?=[^\}]*\})) # What to search for
(?<skip>^[^\{]*\{|\}[^\{]*\{) # What we should skip
)
(?&skip)(*SKIP)(*FAIL) # Skip it
|
(?&needle) # Match it/mx
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'
subst = '\\\\frac'
result = str.gsub(re, subst)
# Print the result of the substitution
puts 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 Ruby, please visit: http://ruby-doc.org/core-2.2.0/Regexp.html