Why does the following only replace the first instance of the pattern?
‘|\ |\ |’.gsub(/|\ |/, “||”)
Why does the following only replace the first instance of the pattern?
‘|\ |\ |’.gsub(/|\ |/, “||”)
On 11/9/2010 11:03 AM, Sd He wrote:
Why does the following only replace the first instance of the pattern?
‘|\ |\ |’.gsub(/|\ |/, “||”)
The pattern is matching pairs of | characters with content in between.
Once it matches the first instance, there is only a single | character
remaining in the original string. The replacement text is not taken
into consideration.
Try the following modification instead. It uses a lookahead assertion
to avoid consuming the trailing | character in each sequence:
‘|\ |\ |’.gsub(/|\ (?=|)/, “|”)
Since the search does not consume the trailing | character, the
replacement string is only a single | character rather than a double.
-Jeremy
I see. Thanks a lot, especially for the lightning response!
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.
Sponsor our Newsletter | Privacy Policy | Terms of Service | Remote Ruby Jobs