2012-02-02 49 views
4
my_string = 'Here's the #: 49848! - but will dashes, commas & stars (*) show?' 

puts src.gsub(/\d|\W/, "") 

即可以刪除or(「|」)。刪除非gsub(/ d | W /,「」)的非字符的較短方法

以下是我到這裏的方式,我可以縮短嗎?

src = "Here's the #: 49848! - but will dashes, commas & stars (*) show?" 
puts "A) - " + src 
puts "B) - " + src.gsub(/\d\s?/, "") 
puts "C) - " + src.gsub(/\W\s?/, "") 
puts "D) - " + src.gsub(/\d|\W\s?/, "") 
puts "E) - " + src.gsub(/\d|\W/, "") 
puts "F) - " + src 

A) - Here's the #: 49848! - but will dashes, commas & stars (*) show? 
B) - Here's the #: ! - but will dashes, commas & stars (*) show? 
C) - Heresthe49848butwilldashescommasstarsshow 
D) - Heresthebutwilldashescommasstarsshow 
E) - Heresthebutwilldashescommasstarsshow 
F) - Here's the #: 49848! - but will dashes, commas & stars (*) show? 

n.d. D)和E)是我想要的輸出。只是人物。

+3

這已經很短了。你是否試圖在石頭上雕刻這些代碼? :-) – 2012-02-02 20:53:22

回答

15
my_string = "Here's the #: 49848! - but will dashes, commas & stars (*) show?" 
p my_string.delete('^a-zA-Z') 
#=>"Heresthebutwilldashescommasstarsshow" 
+0

喜歡這個。更具可讀性。 – 2012-02-02 21:10:21

+0

是的,這是最好的。正試圖做到這一點,但不知道刪除選項。該死的很方便! – 2012-02-02 21:12:41

4

我有這樣一個

src.gsub(/[^a-z]/i, "") 

也不短,但更好地在我看來閱讀。

i修飾符使正則表達式獨立,因此a-z也匹配A-Z。一個小的區別是,這個正則表達式也將取代你的未被取代的_

+0

+1有用的知道有一個下劃線選項,因爲可能有兩種情況! :) – 2012-02-03 04:33:33

+0

這個語法的問題是,它也刪除'空格',所以在句子中的所有單詞將被連接在一起,如'thisismycomment' – Magesh 2013-02-14 10:35:35

2

如果你想保留也Unicode字母,用這一個:

/\PL/ 

這所有的非字母字符相匹配。