Ruby's gsub for rearranging a string
Suppose I have a string like "abc | xyz" and I'd like to turn it into "xyz | abc" using only a regular expression substitution. (For this example there may be better ways, but this is a stand-in for something hairier.)
The following code doesn't do what I expect:
x = "abc | xyz"
x = x开发者_高级运维.gsub(/^([^\|\s]*)\s*\|\s*(\S*)/, "\2 | \1")
puts x
Is it obvious what I'm doing wrong? Thanks!
You need to escape the backslashes in your replacement string. For example,
x = "abc | xyz"
x = x.gsub(/^([^\|\s]*)\s*\|\s*(\S*)/, "\\2 | \\1")
puts x
or just
x = "abc | xyz"
x = x.gsub(/^([^\|\s]*)\s*\|\s*(\S*)/, '\2 | \1')
puts x
and for bonus points, a simpler regex:
x = "abc | xyz"
x = x.gsub(/(.*) \| (.*)/, '\2 | \1')
puts x
And there's always more than one way to do it..
"abc | xyz".split(' | ').reverse.join(' | ')
精彩评论