Reputation: 2451
How would you only replace the x that are between bracket in the expression below:
{ x} x {x } x x {} x{x}{ x}
Upvotes: 0
Views: 96
Reputation: 45943
str = '{ x} x {x } x x {} x{x}{ x}'
str.gsub /{\s*x\s*}/, '{z}'
This solution does not preserve the spaces.
Upvotes: 0
Reputation: 89557
You can use this pattern:
txt.gsub(/(?:\G(?!\A)|{(?=[^{}]*}))[^x}]*\Kx/, 'y')
It works with several x too.
details:
(?:
\G # position after the last match
(?!\A) # prevent to match the start of the string
| # OR
{ # an opening curly bracket
(?=[^{}]*}) # ensure there is a closing curly bracket
)
[^x}]* # all that is not an x or a }
\K # remove all on the left from match result
x # literal x
Upvotes: 2
Reputation: 59611
You can use .gsub
with both a look-behind and a look-ahead operator:
# replace all instances of x within curly braces with y
'{ x} x {x } x x {} x{x}{ x}'.gsub(/(?<={)\s*x\s*(?=})/, 'y')
Output:
"{y} x {y} x x {} x{y}{y}"
You will need an slightly alternate approach to 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}"
Upvotes: 2