2012-10-04 33 views
3

我現在開始使用紅寶石,並且在課程的作業中,它被要求操作字符串,這引發了一個問題。刪除字符串中的所有字符?

給定一個字符串,鏈接如下:

I'm the janitor, that's what I am! 

的任務是從字符串中刪除一切,但字符,這樣的結果是實現,這將是

IamthejanitorthatswhatIam 

一種方式

"I'm the janitor, that's what I am!".gsub(" ", "").gsub(",","").gsub("'","").gsub("!","") 

這個工程,但它看起來很笨拙。處理這個任務的另一種方法可能是正則表達式。有沒有更多的「紅寶石」 - 實現這一目標?

在此先感謝

+0

'GSUB( 「[^ A-ZA-Z]」, 「」)'應該刪除一切,是不是英文字母。 – nhahtdh

+0

我想你的意思是'/ [^ a-zA-Z] /'.. –

+0

@AdamEberlin:我不確定ruby語法,因爲我沒有使用它。我只知道正則表達式。 – nhahtdh

回答

4

使用正則表達式,而不是字符串.gsub,像/\W/,它匹配非單詞字符:

ruby-1.9.3-p194 :001 > x = "I'm the janitor, that's what I am!" 
=> "I'm the janitor, that's what I am!" 

ruby-1.9.3-p194 :002 > x.gsub(/\W/, '') 
=> "ImthejanitorthatswhatIam" 

由於@nhahtdh指出,這包括數字和下劃線。

可以完成這個任務沒有這樣一個正則表達式是/[^a-zA-Z]/

ruby-1.9.3-p194 :001 > x = "I'm the janitor, that's what I am!" 
=> "I'm the janitor, that's what I am!" 

ruby-1.9.3-p194 :003 > x.gsub(/[^a-zA-Z]/, "") 
=> "ImthejanitorthatswhatIam" 
+2

我不知道OP想要什麼,但'\ W'是除英文字母上下以外的所有內容,** 0-9數字**和**下劃線**。 – nhahtdh

相關問題