From: Brian Candler Date: 2012-09-03T21:27:16+09:00 Subject: Re: Extract # Number from a string Robert Klemme wrote in post #1074406: > On Mon, Sep 3, 2012 at 9:44 AM, Brian Candler > wrote: >> if old_string =~ /#([0-9]+)/ >> new_string = $1 >> else >> puts "Couldn't find it" >> end > > Or use String#[]: ... > irb(main):009:0> arr.map {|s| s[/(?<=#)\d+/]} ...although the positive lookbehind assertion (?<=...) is a somewhat esoteric feature of regexps. You can avoid it using the form String#[regexp, fixnum] to get just the captured value that you are interested in. >> s = "this is a #123 string" => "this is a #123 string" >> s[/#(\d+)/, 1] => "123" Another option is to use String#match or Regexp#match, which return a MatchData object, that in turn you can query for the captures. >> s = "this is a #123 string" => "this is a #123 string" >> s.match(/#(\d+)/) => # >> s.match(/#(\d+)/)[1] => "123" >> /#(\d+)/.match(s)[1] => "123" There's certainly More Than One Way To Do It :-) -- Posted via http://www.ruby-forum.com/.