如何找到Ruby中字符串中特殊字符之间的文本值?

问题描述:

很新的红宝石,如何找到Ruby中字符串中特殊字符之间的文本值?

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

我怎样才能找到最后两个前锋之间的值斜线?在这种情况下,该值为'xml'...我不能使用绝对定位,因为'/'的数目会随文本而变化,但是我需要的值始终位于最后两个之间/

我只能找到关于如何在字符串中查找特定单词的示例,但在这种情况下,我不知道单词的价值,因此这些示例没有帮助。

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

你说你确定它总是最后两个斜线之间。这会将你的字符串分成斜杠数组,然后得到倒数第二个元素。

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

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

如果你有红宝石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