简体   繁体   English

如何在Ruby中获取两个字符之间的字符串?

[英]How can I get a string between two characters in Ruby?

Okay if I have a string that is a full file path like "Folder/New Folder/test.csv" . 好的,如果我有一个完整文件路径的字符串,例如"Folder/New Folder/test.csv" How can I get everything between the /'s ? 如何获得/'s之间的所有信息? So get "New Folder" . 因此,获取"New Folder"

Thanks! 谢谢!

No need to use a regex at all... 完全不需要使用正则表达式...

> File.basename(File.dirname("Folder/New Folder/test.csv"))
=> "New Folder"

You don't necessarily have to use a regex to accomplish this task. 您不一定必须使用正则表达式来完成此任务。

String Split 字符串分割

path = "Folder/New Folder/test.csv"
puts path.split('/')[1]

File Operations 文件操作

path = File.dirname("Folder/New Folder/test.csv")
puts File.basename(path)

Regex 正则表达式

path = "Folder/New Folder/test.csv"
puts path.scan(/\/(.*)\//)[0]

Using any of these ways, you will get the following output: 使用这些方法中的任何一种,您将获得以下输出:

#=> New Folder

Just do 做就是了

File.dirname( "Folder/New Folder/test.csv" ).split('/')[-1]
# => "New Folder"

If you wish to use regex: 如果您想使用正则表达式:

input = "Folder/New Folder/test.csv"
print input.scan(/\/(.*)\//).flatten

You can do this easily using a regular expression. 您可以使用正则表达式轻松完成此操作。 Note this will yield whatever is between the 1st and 2nd / . 请注意,这将产生介于1st和2nd /之间的任何值。 So if your String would be "some/longer/path/than/original" , it would yield "longer" . 因此,如果您的String是"some/longer/path/than/original" ,它将产生"longer"

path = "Folder/New Folder/test.csv"
p path[%r{/([^/]+)/}, 1]
# => "New Folder"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何根据Ruby中的字符数分割字符串? - How can I split a string in Ruby based on the number of characters between it? 如何在ruby中使用特殊字符的两个字符串之间获取文本? - How to get text between two strings with special characters in ruby? 如何在 Ruby 中返回两个单独字符串之间的不常见字符? - How can I return the uncommon characters between two separate strings in Ruby? 如何在 ruby 的字符串中的每个字符之间添加字符? - How do I add characters between each character in a string in ruby? 在字符串上使用Ruby,如何使用RegEx在字符串的两个部分之间进行切片? - Using Ruby on a string, how can I slice between two parts of the string using RegEx? 如何从Rails中的ruby字符串中获取双引号字符 - How can i get double quoted characters from a string in ruby on rails 如何在 Ruby 的字符串中检测某些 Unicode 字符? - How can I detect certain Unicode characters in a string in Ruby? 如何使用unicode字符扫描ruby字符串? - How can I scan a ruby string with unicode characters? 如何从 Ruby 中的字符串中去除制表符? - How can I strip tab characters from a string in Ruby? 如何在Neo4j ruby​​中的两个ActiveNode之间获取所有ActiveRel? - How can I get all ActiveRel between two ActiveNode in Neo4j ruby?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM