我有路径解析的正则表达式。下面是正则表达式的一部分,它重复多次。
dir_pattern = /
\/?
(?<dir> #pattern to catch directory
[^[:cntrl:]\/\n\r]+ #directory name
)
(?=\/) #indistinguishable from file otherwise
/x
输入:
/really/long/absolute/path/to/file.extension
期望的输出:
to/really/long/file.extension
我想切断一些(不是所有目录)并重新排序剩余的目录。我怎么能做到这一点?
由于我已经使用正则表达式来过滤所需的文件,我想继续使用它们。
答案 0 :(得分:1)
好的,这是基于上面发布的新信息的正则表达式答案:
rx = /\/[^\/]+/i
# matches each character that is not a '/'
# this ensures any character like a '.' in a file name or the dot
# in the extension is kept.
path = '/really/long/absolute/path/to/file.extension'
d = path.scan(rx)
# returns an array of all matches ["/really", "/long", "/absolute", "/path", "/to", "/file.extension"]
new_path = [y[4], y[0], y[1], y[-1]].join
# returns "to/really/long/file.extension"
让我们将它包装在一个方法中:
def short_path(path, keepers)
rx = /\/[^\/]+/i
d = path.scan(rx)
new_path = []
keepers.each do |dir|
new_path << d[dir]
end
new_path << d[-1]
new_path.join
end
用法:只需通过方法路径和要保留在新订单中的位置数组。
path = '/really/long/absolute/path/to/file.extension'
new_path = short_path(path, [4,0,1])
# returns '/to/really/long/file.extension'
如果你需要删除相对路径的第一个'/':
new_path.sub!(/\//, '')
使用字符串操作而不使用正则表达式的旧答案...
x = "01234567 capture me!"
puts "#{x[7]}#{x[4]}#{x2}"
#=> "742"