簡體   English   中英

紅寶石正則表達式:如何從URL中提取字符串

[英]ruby regex: How to extract string from url

對rubular不太熟悉,想知道如何使用Ruby regex從中提取“ postreview-should-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", "\"}"]

仍在嘗試各種方法。 提前致謝。

要從給定的字符串中提取該子字符串,可以使用以下內容進行匹配而不是拆分。

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

工作演示

您可以使用string.scan而不是string.split

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

以此拆分並獲得第二個組件。請參閱演示。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM