2

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
  • 4
    Welcome to SO! Please provide an attempt in code. Commented Aug 12, 2020 at 23:23
  • 1
    So basically string[%r[/Volumes/.*/\.xml]]? Commented Aug 12, 2020 at 23:30

2 Answers 2

1

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"]
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.