I have a string
how can i extract the number after the # sign?
Use a reegular expression match.
old_string = “this is _ a 76string / #123 like 456”
if old_string =~ /#([0-9]+)/
new_string = $1
else
puts “Couldn’t find it”
end
There are shortcuts, e.g. \d is the same as [0-9]
Google for loads of regular expression tutorials on the Internet. Ruby
is very similar, with some minor differences (e.g. to match start and
end of string use \A and \z respectively)
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+)/)
=> #<MatchData “#123” 1:“123”>
s.match(/#(\d+)/)[1]
=> “123”
/#(\d+)/.match(s)[1]
=> “123”
…although the positive lookbehind assertion (?<=…) is a somewhat
esoteric feature of regexps.
I am not sure I agree on “esoteric”. If you had said it is a more
recent feature, then I’d readily agree. I can name off the top of my
head at least three mainstream programming languages which support it
(Java, Ruby >= 1.9 and Perl).
You can avoid it using the form
String#[regexp, fixnum] to get just the captured value that you are
interested in.