开发者

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(' | ')
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜