开发者

String that can contain multiple numbers - how do I extract the longest number?

I have a string tha开发者_如何学JAVAt

  • contains at least one number
  • can contain multiple numbers

Some examples are:

https://www.facebook.com/permalink.php?story_fbid=53199604568&id=218700384
https://www.facebook.com/username_13/posts/101505775425651120
https://www.facebook.com/username/posts/101505775425699820

I need a way to extract the longest number from the string. So for the 3 strings above, it would extract

53199604568
101505775425651120
101505775425699820

How can I do this?


#get the lines first
text = <<ENDTEXT
https://www.facebook.com/permalink.php?story_fbid=53199604568&id=218700384
https://www.facebook.com/username_13/posts/101505775425651120
https://www.facebook.com/username/posts/101505775425699820
ENDTEXT
lines = text.split("\n")

#this bit is the actual answer to your question
lines.collect{|line| line.scan(/\d+/).sort_by(&:length).last}

Note that i'm returning the numbers as strings here. You could convert them to numbers with to_i


parse the list (to get an int array), then use the Max function. array.Max for syntax.


s = "https://www.facebook.com/permalink.php?story_fbid=53199604568&id=218700384"
s.scan(/\d+/).max{|a,b| a.length <=> b.length}.to_i
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜