ruby正则表达式匹配最后两个分隔符之间的字符串

时间:2013-08-03 18:24:46

标签: ruby regex

我需要匹配正则表达式

中最后两个'/'之间的所有内容

例如:for string tom / jack / sam / jill / --->我需要匹配吉尔

并且在这种情况下还需要匹配tom / jack / sam(没有最后的'/')

赞赏的想法!

2 个答案:

答案 0 :(得分:0)

如果您想要的是一个字符串tom/jack/sam/jill/,则会提取两个组:jilltom/jack/sam/。 您需要的正则表达式为:^((?:[^\/]+\/)+)([^\/]+)\/$

请注意,regexp不接受字符串开头的/,并在字符串末尾请求/

看看:http://rubular.com/r/mxBYtC31N2

答案 1 :(得分:0)

1)

str = "tom/jack/sam/jill/"

*the_rest, last = str.split("/")
the_rest = the_rest.join("/")

puts last, the_rest

--output:--
jill
tom/jack/sam

2)

str = "tom/jack/sam/jill/"

md = str.match %r{
    (.*)        #Any character 0 or more times(greedy), captured in group 1
    /           #followed by a forward slash
    ([^/]+)     #followed by not a forward slash, one or more times, captured in group 2
}x              #Ignore whitespace and comments in regex

puts md[2], md[1] if md

--output:--
jill
tom/jack/sam