Extract # Number from a string

Hi

I have a string
how can i extract the number after the # sign?

examples:

old_string = “this is _ a 76string / #123 like 456”
new_string = “123”

old_string = “435 bill#198777 bgt”
new_string = “198777”

old_string = “my_name#9_is?”
new_string =“9”

Thanks

Erez Ben shoham wrote in post #1074385:

Hi

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)

Robert K. wrote in post #1074406:

On Mon, Sep 3, 2012 at 9:44 AM, Brian C. [email protected]
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+)/)
=> #<MatchData “#123” 1:“123”>
s.match(/#(\d+)/)[1]
=> “123”
/#(\d+)/.match(s)[1]
=> “123”

There’s certainly More Than One Way To Do It :slight_smile:

On Mon, Sep 3, 2012 at 2:27 PM, Brian C. [email protected]
wrote:

Robert K. wrote in post #1074406:

irb(main):009:0> arr.map {|s| s[/(?<=#)\d+/]}

…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.

Right.

There’s certainly More Than One Way To Do It :slight_smile:

If anything, that is true. :slight_smile:

Cheers

robert

On Mon, Sep 3, 2012 at 9:44 AM, Brian C. [email protected]
wrote:

if old_string =~ /#([0-9]+)/
new_string = $1
else
puts “Couldn’t find it”
end

Or use String#[]:

irb(main):006:0> arr = [“this is _ a 76string / #123 like 456”,
irb(main):007:1* “435 bill#198777 bgt”,
irb(main):008:1* “my_name#9_is?”]
=> [“this is _ a 76string / #123 like 456”, “435 bill#198777 bgt”,
“my_name#9_is?”]
irb(main):009:0> arr.map {|s| s[/(?<=#)\d+/]}
=> [“123”, “198777”, “9”]

Kind regards

robert