regex - Replace nested expressions using Ruby -
how replace x between bracket in expression below:
{ x} x {x } x x {} x{x}{ x}
without preserving spaces inside braces
you can use .gsub both look-behind , look-ahead operator:
# replace instances of x within curly braces y '{ x} x {x } x x {} x{x}{ x}'.gsub(/(?<={)\s*x\s*(?=})/, 'y') output:
"{y} x {y} x x {} x{y}{y}" preserving spaces inside braces
you need alternate approach preserving spaces:
'{ x} x {x } x x {} x{x}{ x}'.gsub(/{(\s*)x(\s*)}/, '{\1y\2}') output:
"{ y} x {y } x x {} x{y}{ y}"
Comments
Post a Comment