Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get part of string after some word with Ruby?

Tags:

string

regex

ruby

I have a string containing a path:

/var/www/project/data/path/to/file.mp3

I need to get the substring starting with '/data' and delete all before it. So, I need to get only /data/path/to/file.mp3.

What would be the fastest solution?

like image 562
Alve Avatar asked Dec 05 '25 19:12

Alve


2 Answers

'/var/www/project/data/path/to/file.mp3'.match(/\/data.*/)[0]
=> "/data/path/to/file.mp3"
like image 72
megas Avatar answered Dec 08 '25 11:12

megas


could be as easy as:

string = '/var/www/project/data/path/to/file.mp3'

path = string[/\/data.*/]

puts path
=> /data/path/to/file.mp3

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!