benji
benji

Reputation: 2451

Replace nested expressions using Ruby

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

Answers (3)

B Seven
B Seven

Reputation: 45943

str = '{ x} x {x } x x {} x{x}{  x}'    
str.gsub /{\s*x\s*}/, '{z}'

and http://rubular.com/

This solution does not preserve the spaces.

Upvotes: 0

Casimir et Hippolyte
Casimir et Hippolyte

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

Martin Konecny
Martin Konecny

Reputation: 59611

Without preserving spaces inside the braces

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}"

Preserving spaces inside the braces

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

Related Questions