开发者

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 e开发者_运维问答xample 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?


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:

  • String#scan
  • Array#[]
  • Array#join


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


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜