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.

chickensmitten
  • 477
  • 6
  • 16

3 Answers3

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

hwnd
  • 69,796
  • 4
  • 95
  • 132
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"
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
  • 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. – chickensmitten Jan 13 '15 at 04:49
  • print the index 0 and get the string you want. – Avinash Raj Jan 13 '15 at 04:56
0
\/(?!.*\/)

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

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

vks
  • 67,027
  • 10
  • 91
  • 124