Extract string from within a longer string | Ruby

Viewed 71

I'm trying to extract a sentence from a long string using Ruby.

Example:

Hi There the file is in this directory: /Volumes/GAW-FS01/08_Video/02_Projects/ Plus/S/metadata.xml Thank you for your inquiry.

It should return: /Volumes/GAW-FS01/08_Video/02_Projects/ Plus/S/metadata.xml The beginning always include "/Volume" and it has ti end with ".xml"

Thank you

2 Answers

You're probably looking for this -

long_string = <<file
Hi There the file is in this directory: /Volumes/GAW-FS01/08_Video/02_Projects/Plus/S/metadata.xml Thank you for your inquiry.Hi There the file is in this directory: /Volumes/GAW-def/08_Video/02_Projects/Plus/S/metadata.xml Thank you for your inquiry.Hi There the file is in this directory: /Volumes/GAW-FS01/08_Video/02_Projects/hello/S/metadata.xml Thank you for your inquiry.
file

long_string.split.select{ |word| word.starts_with?("/Volumes") && word.end_with?(".xml") }

It'll give you array of paths which match your condition like follow -

["/Volumes/GAW-FS01/08_Video/02_Projects/Plus/S/metadata.xml", "/Volumes/GAW-def/08_Video/02_Projects/Plus/S/metadata.xml", "/Volumes/GAW-FS01/08_Video/02_Projects/hello/S/metadata.xml"]

There are many ways to do this.

string = "Hi There the file is in this directory: /Volumes/GAW-FS01/08_Video/02_Projects/ Plus/S/metadata.xml Thank you for your inquiry." 

Funky:

"Volume#{string[/Volume(.*?).xml/, 1]}.xml"

Funkier, find the index of the strings and use the range to return the desired string

first = "Volume"
last = ".xml"
string[(string.index(first)) .. (string.index(last) + last.length)]
 => "Volumes/GAW-FS01/08_Video/02_Projects/ Plus/S/metadata.xml "

Not so funky, split the string by the start and end points and return the desired string

"Volume#{string.split('Volume').last.split('.xml').first}.xml"
 => "Volumes/GAW-FS01/08_Video/02_Projects/ Plus/S/metadata.xml"

Lastly, the way you'd probably want to do this

string[/Volume(.*?).xml/, 0]
=> "Volumes/GAW-FS01/08_Video/02_Projects/ Plus/S/metadata.xml"

You notice the first and last options are the same, despite the int passed changing between 0 and 1. The 0 captures the regular expressions used to match where the 1 does not.

Related