2012-02-02 44 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/ 

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