user1903663
user1903663

Reputation: 1725

I need to extract part of a variable string with ruby, how can this be done?

I have a string as follows:

"/v1/Account/MAMTE4MTHJNJRKODBIMD/Call/34b4209a-5d97-11e3-9fb6-3d0f528c3bba/"

I want to extract the bit between Account/ and /Call, in other words: "MAMTE4MTHJNJRKODBIMD"

I have tried

string.delete('/v1/Account/')

with no success.

'/v1/Account/' will always be the same and '/Call/' will always be the same but the remainder of the string to the right of '/Call/' will vary.

How can I do this guys? Thank you!

Upvotes: 0

Views: 55

Answers (4)

I just want to point out that you can use

%r{/Account/(.*)/Call}

instead of escaping all backslashes. Yet another possible solution using String#scan:

string.scan(%r{/Account/(.*)/Call}).join

Upvotes: 0

Roman Kiselenko
Roman Kiselenko

Reputation: 44360

=> str = "/v1/Account/MAMTE4MTHJNJRKODBIMD/Call/34b4209a-5d97-11e3-9fb6-3d0f528c3bba/"
=> str.split('/')[3]
=> "MAMTE4MTHJNJRKODBIMD"

Upvotes: 2

Pritesh Jain
Pritesh Jain

Reputation: 9146

use regex String#match

string.match(/\/v1\/Account\/(.*)\/Call\//)[1]

or

string[12..string.index("/Call/")-1]

Upvotes: 0

ckruse
ckruse

Reputation: 9740

The easiest way would be a substring:

id = string[12..31]

If the pattern changes, you can try out a regex:

id = string.gsub(/\/[\/]+\/Account\/([^\/]+)\/.*/, '\1')

Upvotes: 0

Related Questions