1

I have a string from which I want to extract a certain part:

Original String: /abc/d7_t/g-12/jkl/m-n3/pqr/stu/vwx

Result Desired: /abc/d7_t/g-12/jkl/

The number of characters can vary in the entire string. It has alphabets, numbers, underscore and hyphen. I want to basically cut the string after the 5th "/"

I tried a few regex, but it seems there is some mistake with the format.

6
  • 6
    rubular.com is your friend Commented Dec 11, 2012 at 8:25
  • So what's the rule you want to apply? Always cut before pqr? Or after the 6th instance of /? Or the 16th character? Or the 4th digit? What? Clarify this and you'll be halfway there... Commented Dec 11, 2012 at 8:28
  • I did something like this : (/[wW]/[wW]/[wW]/[wW]/[wW]/)....I m not sure how to find a "/" and also w & W doesn't include the symbol '-' which is present in my string at many places Commented Dec 11, 2012 at 8:30
  • @Jean-FrançoisCorbett : The number of characters can vary. I want to cut the string after the 5th "/" Commented Dec 11, 2012 at 8:31
  • 1
    Why not just split it with / and join the first 5 parts with / ? Commented Dec 11, 2012 at 8:39

3 Answers 3

3

If a non-regexp approach is acceptable, how about this:

s.split('/').take(n).join('/')+'/'

Where s if your string (in your case: /abc/d7_t/g-12/jkl/m-n3/pqr/stu/vwx).

def cut_after(s, n)
  s.split('/').take(n).join('/')+'/'
end

Then

cut_after("/abc/d7_t/g-12/jkl/m-n3/pqr/stu/vwx", 5)

should work. Not as compact as a regexp, but some people may find it clearer.

Sign up to request clarification or add additional context in comments.

1 Comment

That's fine if you hate regexes - making it clear that a non-regex solutions are also acceptable would be useful(people, including myself, love to find a regexp fix to solutions with the goal of doing it in regexps ;-))
2

The regexp would be: %r(/(?:[^/]+/){4}). Note that it is a good idea in this case to use the %r literal version to avoid escaping slashes. Unescaped slashes are likely the cause of your format errors.

3 Comments

Please note my comment as well. It's the 6th slash he wants (he forgot to include the first in the count).
Looks like 5 slashes to me. I just double counted. Also, before I posted I checked my result in irb against his desired result.
wow, my bad, I must have had an error in my original Regex I tested. -.-
1

Match any sequence of chars except '/' 4 times :-

(\/[^\/]+){4}\/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.