Karthi1234
Karthi1234

Reputation: 1017

How to split a string which contains multiple forward slashes

I have a string as given below,

./component/unit

and need to split to get result as component/unit which I will use this as key for inserting hash.

I tried with .split(/.\//).last but its giving result as unit only not getting component/unit.

Upvotes: 2

Views: 1329

Answers (4)

Sagar Pandya
Sagar Pandya

Reputation: 9497

Using a positive lookbehind, you could do use regex:

reg  = /(?<=\.\/)[\w+\/]+\w+\z/

Demo

str  = './component'
str2 = './component/unit'
str3 = './component/unit/ruby'
str4 = './component/unit/ruby/regex'

[str, str2, str3, str4].each { |s| puts s[reg] }
#component
#component/unit
#component/unit/ruby
#component/unit/ruby/regex

Upvotes: 0

Felix
Felix

Reputation: 4716

All the other answers are fine, but I think you are not really dealing with a String here but with a URI or Pathname, so I would advise you to use these classes if you can. If so, please adjust the title, as it is not about do-it-yourself-regexes, but about proper use of the available libraries.

Link to the ruby doc:

https://docs.ruby-lang.org/en/2.1.0/URI.html and https://ruby-doc.org/stdlib-2.1.0/libdoc/pathname/rdoc/Pathname.html

An example with Pathname is:

require 'pathname'

pathname = Pathname.new('./component/unit')
puts pathname.cleanpath # => "component/unit"
#    pathname.to_s      # => "component/unit"

Whether this is a good idea (and/or using URI would be cool too) also depends on what your real problem is, i.e. what you want to do with the extracted String. As stated, I doubt a bit that you are really intested in Strings.

Upvotes: 2

Eric Duminil
Eric Duminil

Reputation: 54263

Your regex was almost fine :

split(/\.\//)

You need to escape both . (any character) and / (regex delimiter).

As an alternative, you could just remove the first './' substring :

'./component/unit'.sub('./','')
#=> "component/unit"

Upvotes: 5

Oleksandr Holubenko
Oleksandr Holubenko

Reputation: 4440

I think, this should help you:

string = './component/unit'

string.split('./') 
#=> ["", "component/unit"]

string.split('./').last
#=> "component/unit"

Upvotes: 5

Related Questions