dr.qwerty
dr.qwerty

Reputation: 55

How to change special symbols in string?

For example I have a string

s = "start |foo bar|, middle, |reg ex| end"

and I would like to change | on square brackets, to get

"start [foo bar], middle, [reg ex] end"

How can I achieve it by using regex? At least, I would like to capture |foo bar| and |reg ex|, but my method:

/\|.+\|/

captures |foo bar|, middle, |reg ex|

s.match(/\|.+\|/)[0] # => "|foo bar|, middle, |reg ex|"

Upvotes: 3

Views: 76

Answers (2)

Ankun
Ankun

Reputation: 444

"start |foo bar|, middle, |reg ex| end".gsub(/\|(.+?)\|/, '[\1]')
=> "start [foo bar], middle, [reg ex] end" 

"start |foo bar|, middle, |reg ex| end".gsub(/\|(.+?)\|/) do |str|
  puts $1
end

foo bar
reg ex
=> "start , middle,  end"

Upvotes: 2

codaddict
codaddict

Reputation: 454940

Try making the regex non-greedy:

/\|.+?\|/

or

/\|[^|]+\|/

Upvotes: 2

Related Questions