2012-04-25 67 views
1

很新的紅寶石,如何找到Ruby中字符串中特殊字符之間的文本值?

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

我怎樣才能找到最後兩個前鋒之間的值斜線?在這種情況下,該值爲'xml'...我不能使用絕對定位,因爲'/'的數目會隨文本而變化,但是我需要的值始終位於最後兩個之間/

我只能找到關於如何在字符串中查找特定單詞的示例,但在這種情況下,我不知道單詞的價值,因此這些示例沒有幫助。

回答

2

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

你說你確定它總是最後兩個斜線之間。這會將你的字符串分成斜槓數組,然後得到倒數第二個元素。

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

這是正確的,工作完美,TY。 – raffian 2012-04-25 21:57:21

0

如果你有紅寶石1.9或更高版本:

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 = $& 
+0

忘了提及,我使用的是1.8,但無論如何謝謝 – raffian 2012-04-25 21:53:11

+0

@RaffiM:在這種情況下,你可以在開始時刪除'(?<= \ /)',但是然後正則表達式不能確保那裏*在字符串中至少有兩個斜槓。如果這不是問題,那麼正則表達式應該沒問題。 – 2012-04-25 21:55:10

相關問題