1

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?

1
  • 4
    You are searching for the first 2 digits not integers. If you would search for the first 2 integers your result would be 67411014. Commented Sep 3, 2011 at 23:23

3 Answers 3

7

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:

Sign up to request clarification or add additional context in comments.

Comments

5

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

1 Comment

With added ruby: my_string.match(/^\D*(\d)\D*(\d)/).captures.join. This will return the string representation of the two first digits in my_string.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.