Mike
Mike

Reputation: 1361

ruby regex finding first two numbers in a string

If I have a string like

6d7411014f

I want to read the the occurrence of first two integers and put the final number in a variable

Based on above example my variable would contain 67

more examples:

d550dfe10a

variable would be 55

What i've tried is \d but that gives me 6. how do I get the second number?

Upvotes: 1

Views: 4227

Answers (3)

mu is too short
mu is too short

Reputation: 434635

I'd use scan for this sort of thing:

n = my_string.scan(/\d/)[0,2].join.to_i

You'd have to decide what you want to do if there aren't two numbers though.

For example:

>> '6d7411014f'.scan(/\d/)[0,2].join.to_i
=> 67

>> 'd550dfe10a'.scan(/\d/)[0,2].join.to_i
=> 55

>> 'pancakes'.scan(/\d/)[0,2].join.to_i
=> 0

>> '6 pancakes'.scan(/\d/)[0,2].join.to_i
=> 6

References:

Upvotes: 7

peakxu
peakxu

Reputation: 6675

Building off of sidyll's answer,

string = '6d7411014f'
matched_vals = string.match(/^\D*(\d)\D*(\d)/)
extracted_val = matched_vals[1].to_i * 10 + matched_vals[2].to_i

Upvotes: 0

sidyll
sidyll

Reputation: 59287

I really can't answer this exactly in Ruby, but a regex to do it is:

/^\D*(\d)\D*(\d)/

Then you have to concatenate $1 and $2 (or whatever they are called in Ruby).

Upvotes: 5

Related Questions