ruby 正则表达式:如何从 url 中提取字符串
ruby regex: How to extract string from url
对 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", "\"}"]
还在尝试各种方法。提前致谢。
您可以使用 string.scan
而不是 string.split
> "{\"source_url\"=>\"http://testing.com/projects/postreview-should-be-the-cause\"}".scan(/(?<=\/)[^\/"]*(?=[^\/]*$)/)[0]
=> "postreview-should-be-the-cause"
要从给定的字符串中提取该子字符串,您可以使用以下内容来匹配而不是拆分。
result = url.match(/\w+(?:-\w+)+/)
\/(?!.*\/)
被 this.And 拆分获得第二个 component.See 演示。
对 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", "\"}"]
还在尝试各种方法。提前致谢。
您可以使用 string.scan
而不是 string.split
> "{\"source_url\"=>\"http://testing.com/projects/postreview-should-be-the-cause\"}".scan(/(?<=\/)[^\/"]*(?=[^\/]*$)/)[0]
=> "postreview-should-be-the-cause"
要从给定的字符串中提取该子字符串,您可以使用以下内容来匹配而不是拆分。
result = url.match(/\w+(?:-\w+)+/)
\/(?!.*\/)
被 this.And 拆分获得第二个 component.See 演示。