tags:

views:

57

answers:

4

I need to write a regular expression in ruby for finding a string like 'some' and then replace it with say 'xyz.some'. How do I go about it?

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

That doesn't look like you need a regex - plain old gsub will do:

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

You find 'some' (or anything other) and then you can use \0 in replace string (watch for quoting, you need to use \\0 in "..." string) to place all your regex matched. Or you can group matches in your regex and use \1 - \9 in your replace string. To place non matching group, just use (?: ).

MBO
+2  A: 

If 'some' can be any arbitrary string (unknown at the time of writing the script), Use \1 to use the matched group (by position) in your replacement string.

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"
Gishu