5
my_string = 'Here's the #: 49848! - but will dashes, commas & stars (*) show?'

puts src.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?

nd D) 和 E) 是我想要的输出。只是字符。

4

3 回答 3

19
my_string = "Here's the #: 49848! - but will dashes, commas & stars (*) show?"
p my_string.delete('^a-zA-Z')
#=>"Heresthebutwilldashescommasstarsshow"
于 2012-02-02T21:07:48.043 回答
4

我有这个

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

也不短,但在我看来更好读。

i修饰符使正则表达式大小写独立,因此也a-z匹配A-Z. 一个小的区别是这个正则表达式也会替换_你没有替换的。

于 2012-02-02T21:18:51.657 回答
2

如果您还想保留 unicode 字母,请使用这个:

/\PL/

这匹配所有非字母字符。

于 2012-02-03T13:05:10.197 回答