Best way to extract data from a string?

Hi
I have a string
str = “file name_Width34.56_Height45.97_.jpg”

what is the best way to extract the the data from the string?

file name => “file name.jpg”
width => “34.56”
hieght => “45.97”

2012/10/14 Erez Ben shoham [email protected]


Posted via http://www.ruby-forum.com/.

string = “file name_Width34.56_Height45.97_.jpg”
string =~ /(.+)_Width(\d+.\d+)Height(\d+.\d+).jpg/
puts $1, $2, $3

http://rubular.com is your friend, try it.

Hi,

the best way would be to use a proper data format. But I assume the
strings are given and cannot be changed?

Use regular expressions

@ImranNazirMir Follow Me on Pinterest
http://pinterest.com/imrannazirmir/ View Imran Nazir’s profile on
LinkedIn http://uk.linkedin.com/pub/imran-nazir/2/402/a57

str = ‘file name_Width34.56_Height45.97_.jpg’

name, width, height, ext = str.split(’_’)
name << ext

width = width[5…-1]
height = height[6…-1]

puts name, width, height

–output:–
file name.jpg
34.56
45.97

so we created a photoshop script that automatically creates the small
version jpgs and inserts the original width height data to the name of
the file.

Whoever wrote that script was not thinking ahead.

7stud – wrote in post #1079843:

Whoever wrote that script was not thinking ahead.

Very true. Anything (even a crappy CSV) would have been better than
mangling all data in the file name. What if the original filename
already includes an underscore (which is not that unlikely)? Good luck
parsing it.

Jan E. wrote in post #1079799:

Hi,

the best way would be to use a proper data format. But I assume the
strings are given and cannot be changed?

sorry for my English
the purpose of this is
there are photoshop .psd files localy on a mac.
and we need to upload small jpgs versions of them to a web app with the
original width and height data in the fastest hassle free way.
the upload process changes the size of the images.
so we created a photoshop script that automatically creates the small
version jpgs and inserts the original width height data to the name of
the file.
then the user drag and drop the small jpgs to the browser and then we
upload the images and update the data accordingly.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs