Michael Michael - 4 months ago 9
Ruby Question

How to extract part of the string which comes after given substring?

For example I have url string like:

https://abc.s3-something.amazonaws.com/subfolder/1234/5.html?X-Amz-Credential=abcd12bhhh34-1%2Fs3%2Faws4_request&X-Amz-Date=2016&X-Amz-Expires=3&X-Amz-SignedHeaders=host&X-Amz-Signature=abcd34hhhhbfbbf888ksdskj


From this string I need to extract number 1234 which comes after subfolder/. I tried with gsub but no luck. Any help would be appreciated.

Answer

Suppose your url is saved in a variable called url. Then the following should return 1234

url.match(/subfolder\/(\d*)/)[1]

Explanation:

url.match(/     # call the match function which takes a regex
  subfolder\/   # search for the first appearance of the string 'subfolder/'
                # note: we must escape the `/` so we don't end the regex early
  (\d*)         # match any number of digits in a capture group,
/)[1]           # close the regex and return the first capture group
Comments