From: dblack@... Date: 2006-12-13T03:07:11+09:00 Subject: Re: Newbie questions Hi -- On Wed, 13 Dec 2006, Jason Mayer wrote: > On 12/12/06, Dav Jones wrote: >> >> Thanks. I've got it reading in a file and checking each line against a >> regular expression. >> >> How would I go about taking individual sections of a line? >> i.e. if the word 'example:' appears on a line then it takes that and a >> few characters before or after it (it will be something specific its >> just the question is in general here) so for >> blah blah blah example: twenty blah blah >> it returns me 'example: twenty' >> >> -- >> Posted via http://www.ruby-forum.com/. >> >> > Complete nuby here, but I'll give it a shot: > > example = "blah blah example: twenty." > re = /example: .+[^ \t\n\r\f]/ You can use \S (non-whitespace) for your character class. (I do have this nagging feeling that there was some strange edge case involving whitespace and character classes... so test it and make sure :-) > stuff = re.match(example) > puts stuff > > Output: > C:\ruby\programs>ruby regex2.rb > example: twenty. You'll get the right output from puts here, but you're actually puts'ing the whole MatchData object, not a substring of the original string. So if you do anything string-like with it, something will go wrong. You can do, instead: stuff = re.match(example) substring = stuff[0] if stuff at which point substring will either be the matched part of the string, or it will be nil (thanks to the fact that "if" expressions evaluate to nil if they're false and have no "else"). Another thing you can do is: example[/example: .+\S+/] That's a nice handy way to grab a substring via a pattern. David -- Q. What's a good holiday present for the serious Rails developer? A. RUBY FOR RAILS by David A. Black (http://www.manning.com/black) aka The Ruby book for Rails developers! Q. Where can I get Ruby/Rails on-site training, consulting, coaching? A. Ruby Power and Light, LLC (http://www.rubypal.com)