0

not very familiar with rubular, would like to know how to use Ruby regex to extract "postreview-should-be-the-cause" from

"{\"source_url\"=>\"http://testing.com/projects/postreview-should-be-the-cause\"}"

the best I am getting is

check_user = url.split(/\b(\w+)\b/)
=> ["{\"", "source_url", "\"=>\"", "http", "://", "localhost", ":", "3000", "/", "projects", "/", "postreview", "-", "should", "-", "be", "-", "the", "-", "cause", "\"}"]

Still trying various ways. Thanks in advance.

3 Answers 3

1

To extract that substring from the given string, you could use the following to match instead of split.

result = url.match(/\w+(?:-\w+)+/)

Working Demo

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

2 Comments

I am new to match, just wondering if this is the right way use match? Model.find_by(puts result)
I think I got it, but do let me know if "Model.find_by(puts result)" is valid. =)
0
\/(?!.*\/)

Split by this.And get the second component.See demo.

https://regex101.com/r/sH8aR8/48

Comments

0

You could use string.scan instead of string.split

> "{\"source_url\"=>\"http://testing.com/projects/postreview-should-be-the-cause\"}".scan(/(?<=\/)[^\/"]*(?=[^\/]*$)/)[0]
=> "postreview-should-be-the-cause"

2 Comments

Thanks avinash! wow, didnt know about scan. So far, string.scan gave me this output. check_user = url.scan(/\b(\w+)\b/) => [["source_url"], ["http"], ["localhost"], ["3000"], ["projects"], ["postreview"], ["should"], ["be"], ["the"], ["cause"]], how can I merge them back to "postreview-should-be-the-cause"? cause I need to match this later with another model.
print the index 0 and get the string you want.

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.