0

I am having a problem extracting a substring from a string using regex.

For example I have a string like follows

str = "result[cars][ford]"

Now I need a regex which can extract out cars and ford out of that string so that when

str.match({{regex}})[1]

would provide cars and

str.match({{regex}})[2] 

would provide ford

Now i need that regex inside that curly braces.

Any link that helps to this question are most welcomed.

2
  • Question updated: str always must start with result Commented Aug 8, 2012 at 11:00
  • Well, your string doesn't match this condition Commented Aug 8, 2012 at 11:04

1 Answer 1

2

It's actually simple.

s = "result[cars][ford]"
matches = s.scan(/\[(\w+)\]/).flatten # => ["cars", "ford"]

Here's a demo.

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

3 Comments

Hi, Sergio Tulentsev please see the comment in question.
Well here's what i got with this regex. str = "result[cars][ford]". str.match(/[(\w+)]/)[2] gives me nil
Still it produce the same result for the string str = "whatever[cars][ford]". matches = str.scan(/[(\w+)]/).flatten # => ["cars", "ford"]. How do i get the result only if it starts with result

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.