拆分字符串(字符串包含正则表达式)

时间:2019-05-03 11:16:20

标签: ruby

我想从给定路径中拆分最后一个字符串,该字符串包含一些数字,例如1.625.235,但是此数字每次都不同。不管最后一个字符串应该分割多少个数字。

例如:

string = "C:/chef/cache/Dynatrace-OneAgent-Windows-1.625.235.msi"
output:  Dynatrace-OneAgent-Windows-1.625.235.msi

string = "C:/chef/cache/Dynatrace-OneAgent-Windows-1.181.539.msi"
output:  Dynatrace-OneAgent-Windows-1.181.539.msi

这是我们尝试过的

  • (“ C:/ chef / cache / Dynatrace-OneAgent-Windows-/ \ d。\ d +。\ d + /。msi”)。split('/')[3]
  • (“ C:/ chef / cache / Dynatrace-OneAgent-Windows-'/ \ d。\ d +。\ d + /'。msi”)。split('/')[3]
  • (“ C:/ chef / cache / Dynatrace-OneAgent-Windows-'\ d。\ d +。\ d +'。msi”)。split('/')[3]
  • (“ C:/ chef / cache / Dynatrace-OneAgent-Windows-'(\ d。\ d +。\ d +')。msi”)。split('/')[3]
  • (“ C:/ chef / cache / Dynatrace-OneAgent-Windows-('/ \ d。\ d +。\ d + /')。msi”)。split('/')[3]
  • (“ C:/ chef / cache / Dynatrace-OneAgent-Windows-('\ d。\ d +。\ d +')。msi”)。split('/')[3]

2 个答案:

答案 0 :(得分:4)

如果所需的输出始终是路径末尾的文件名,则也可以使用File.basename

string = "C:/chef/cache/Dynatrace-OneAgent-Windows-1.625.235.msi"
output = File.basename(string) # => "Dynatrace-OneAgent-Windows-1.625.235.msi"

答案 1 :(得分:2)

string="C:/chef/cache/Dynatrace-OneAgent-Windows-1.625.235.msi"

p string.split("/").last

输出

"Dynatrace-OneAgent-Windows-1.625.235.msi"
相关问题