2015-01-13 3 views
0

에서 문자열을 추출하는 방법, 추출 루비 정규식을 사용하는 방법을 알고 싶습니다 "postreview --해야한다 - 더 - 원인"루비 정규식 : Rubular 나 매우 익숙하지 않은 URL

"{\"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", "\"}"] 

아직도 다양한 방법을 시도하고있다. 미리 감사드립니다.

답변

1

의를 사용할 수 있습니다, 당신은 대신 분할의 일치 다음 사용할 수 있습니다. 그럼 ...에 의해

Working Demo

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

나는 이것이 새로운 방법인가? Model.find_by (puts result) – chickensmitten

+0

"Model.find_by (puts result)"가 유효한 지 알려 줘야 겠어. =) – chickensmitten

+0

http://ruby-doc.org/core-2.1.4/Regexp.html#method-i-match – hwnd

0

당신은 주어진 문자열에서 해당 문자열을 추출하려면 string.scan 대신 string.split

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

감사합니다. avinash! 와우, 스캔에 대해 안다. 지금까지 string.scan이 나에게이 결과를주었습니다. check_user = url.scan (/ \ b (\ w +) \ b /) => [ "source_url"], [ "http"], [ "localhost"], [ "3000"], [ "projects"] [postview], [should], [be], [ "the"], [ "cause"]] 어떻게 그들을 "postreview-should-be-the-cause" ? 나중에 다른 모델과 일치시켜야하기 때문입니다. – chickensmitten

+0

색인 0을 인쇄하고 원하는 문자열을 가져옵니다. –