Shpigford
Shpigford

Reputation: 25338

How would I get this portion of the string?

Here's my string:

http://media.example.com.s3.amazonaws.com/videos/1/123ab564we65a16a5w_web.m4v

I want this: 123ab564we65a16a5w

The only variables that will change here are the /1/ and the unique key that I'm trying to pull. Everything else will be exactly the same.

For the /1/ portion, that 1 could be anywhere from 1-3 digits, but will always be numeric.

I'm running Ruby 1.9.2.

Upvotes: 1

Views: 68

Answers (3)

TLS
TLS

Reputation: 3150

Since you've indicated that the value you want will always have a "/" immediately before it (and none after it) and an "_" immediately after it, you could use this generic regex:

^.*/(.*)_.*$

Here's why this would work:

^ matches the beginning of the line

.*/ matches any number of characters up to the slash - this is greedy, so it will go until the last slash in the input value

(.*) matches any number of characters and captures the result

_.* matches an underscore and then any number of characters

$ matches the end of the line

By matching anything up to the last "/" and then anything after the "_", you easily isolate the desired value.

NOTE: I don't know if the Ruby regex syntax is any different than this, so your mileage may vary.

--

EDIT: It looks like in Ruby, you might not need/want the ^ or $ at the beginning and end.

Upvotes: 0

Sergey
Sergey

Reputation: 11908

This is shorter -

s.split(/[/_.]/)[-3]

Upvotes: 0

Josh
Josh

Reputation: 3265

Assuming nothing else changes, here's the regex for it:

http://media.example.com.s3.amazonaws.com/videos/\d{1,3}/(.*)_web.m4v

If there are other changes, you need to let us know all the variables.

Upvotes: 5

Related Questions