Michael Michael - 1 year ago 56
Ruby Question

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

For example I have url string like:


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 Source

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



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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download