raffian
raffian

Reputation: 32056

How to find the text value between special characters in a string in Ruby?

Very new to Ruby,

file_path = "/.../datasources/xml/data.txt"

How can I find the value between the last two forward slashes? In this case that value is 'xml'...I can't use absolute positioning because the number of '/' will vary as will the text , but the value I need is always in between the last two /

I could only find examples on how to find a specific word in a string, but in this case I don't know the value of the word so those examples did not help.

Upvotes: 1

Views: 1091

Answers (2)

shime
shime

Reputation: 9008

file_path.split("/").fetch(-2)

you said you're sure it's always between two last slashes. this splits your string into an array over slashes and then gets the second last element.

"/.../datasources/xml/data.txt".split("/").fetch(-2) => "xml" 

Upvotes: 3

Tim Pietzcker
Tim Pietzcker

Reputation: 336108

If you have Ruby 1.9 or higher:

if subject =~ 
    /(?<=\/) # Assert that previous character is a slash
    [^\/]*   # Match any number of characters except slashes
    (?=      # Assert that the following text can be matched from here:
     \/      #  a slash,
     [^\/]*  #  followed by any number of characters except slashes
     \Z      # and the end of the string
    )        # End of lookahead assertion
    /x
    match = $&

Upvotes: 0

Related Questions