ruby regex:如何从url中提取字符串

时间:2015-01-13 04:42:18

标签: ruby regex rubular

不太熟悉rubular,想知道如何使用Ruby正则表达式从

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

我得到的最好的是

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

仍在尝试各种方式。提前谢谢。

3 个答案:

答案 0 :(得分:1)

要从给定字符串中提取该子字符串,您可以使用以下内容进行匹配而不是分割。

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

Working Demo

答案 1 :(得分:0)

您可以使用string.scan代替string.split

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

答案 2 :(得分:0)

\/(?!.*\/)

由此分开。并获得第二个组件。参见演示。

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