Supersonic
Supersonic

Reputation: 430

What is the most efficient way to search for a sub-string

In the below string I would like to get the revision number which is 153. This part is inside the string which beside the text "Revision: 153\n".

string = "Path: blah\blah\nWorking Copy Root Path: blah\blah\nURL: blah\blah\nRelative URL: ^/README.txt\nRepository Root: blah\blah\nRepository UUID: 2d7234b632a-38239d-4384f-9ac3-c05286096652\nRevisio
    n: 153\nNode Kind: file\nSchedule: normal\nLast Changed Author: user_name\nLast Changed Rev: 153\nLast Changed Date: 2014-11-27 11:38:21 +0530 (Thu, 27 Nov 2014)\nText Last Updated: 2014-11-27 12:
    05:24 +0530 (Thu, 27 Nov 2014)\nChecksum: 7ecb9f79f244r4f996e637d6f23\n\n"

Currently I am doing it this way :

string.split('Revision').last.split('Node').first.chomp.gsub(': ','').to_i

Which outputs 153.

Is there any better way to do it?

Upvotes: 0

Views: 52

Answers (2)

Rustam Gasanov
Rustam Gasanov

Reputation: 15791

You can use String's [] and a regular expression here:

string[/Revision:\s(\d+)/, 1]

Upvotes: 2

Ryo
Ryo

Reputation: 2123

You could use a regular expression. For example, something like following:

string.scan(/Revision: (\d+)/)

Clarifying a bit more, if you want to catch multiple occurrences use this.

Upvotes: 1

Related Questions