简体   繁体   中英

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?

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM