简体   繁体   中英

ruby regex: How to extract string from url

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.

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

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"
\/(?!.*\/)

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM