2010-02-01 38 views

回答

1
str = 'lets make some sandwiches' 
xyzstr = str.gsub(/some/, "xyz.some"); 
2

這並不像你需要一個正則表達式 - 普通的老gsub會做:

s = "foo some" 
=> "foo some" 
s.gsub("some", "xyz.some") 
=> "foo xyz.some" 
2
"some string sth".gsub(/some|sth/, 'xyz.\0') 
=> "xyz.some string xyz.sth" 

你會發現「一些」(或任何其他),然後就可以使用\0在替換字符串(注意引用,你需要在"..."字符串中使用\\0)將所有正則表達式匹配。或者您可以在您的正則表達式中將匹配分組,並在替換字符串中使用\1 - \9。要放置非匹配組,請使用(?:)

2

如果「某些」可以在你的字符串替換任意字符串(在寫劇本的時間不詳), 使用\ 1使用匹配的組(按位置)。

a = "the quick brown fox jumped over the lazy dog" 
str_to_find = "the" 

a.gsub(/(#{str_to_find})/, 'xyz.\1') 
# => "xyz.the quick brown fox jumped over xyz.the lazy dog"