如何在最终分隔符后提取子字符串?

时间:2012-11-13 04:15:36

标签: ruby regex

我正在使用Ruby,我想编写一个带有分隔字符串str(由//分隔)的函数,并返回字符串的最后部分,即部分在字符串中的最后一个//之后。例如,给定a//b///cd,它应返回cd

我可以使用正则表达式来执行此操作吗?如果是,我应该使用什么表达式?

1 个答案:

答案 0 :(得分:2)

正如Nhahtdh在他的comment中写道,你可以使用/.*\/\/(.*)/

在Ruby中,它会像

regex = %r{.*               # any character (0 up to infinit-times) till we find the last
           //               # two consecutive characters '/'
           (?<last_part>.*) # any character (0 up to infinit-times)
          }
string = 'a//b///cd'

puts regex.match(string)[:last_part]
#=> cd

您可以在%r的{​​{3}}部分找到ProgrammingRuby

相关问题