From: dblack@... Date: 2006-07-07T19:54:06+09:00 Subject: Re: Regexp Hi -- On Fri, 7 Jul 2006, Fred VD wrote: > Hello, > > I'm new to Ruby and I'm fighting with regexp. > > I would like to replace 'test1<\math>' and 'test2<\math>' by > 'ok' in the string "blabla1 blabla1 test1<\math> blabla2 blabla2 > test2<\math>" > > When I try this : > > @a = "blabla1 blabla1 test1<\math> blabla2 blabla2 > test2<\math>" > @b = @a.gsub(/.+<\math>/,'ok') > > I get "blabla1 blabla1 ok" instead of "blabla1 blabla1 ok blabla2 > blabla2 ok" > > Could you please help me to tune my regexp so it works the way I want ? As I suspect seven or eight people will tell you, you need to make your one-or-more quantifier non-greedy :-) Note the question mark: a = "blabla1 blabla1 test1<\\math> blabla2 blabla2 test2<\\math>" puts a.gsub(/.+?<\\math>/,'ok') I've made a couple of other changes. In a double-quoted string, "\m" is just the letter m. If you want a \ you have to escape it with another \. (Are you sure you don't want a forward slash anyway?) I have a feeling you don't really need instance variables here; if not, it's better to use locals. David -- "To fully realize the potential of Rails, it's crucial that you take the time to fully understand Ruby--and with "Ruby for Rails" David has provided just what you need to help you achieve that goal." -- DAVID HEINEMEIER HANSSON, in the foreword to RUBY FOR RAILS. Complete foreword & sample chapters at http://www.manning.com/black!