删除非字符的方法比gsub更短(/ \ d | \ W /,"")

时间:2012-02-02 20:50:23

标签: ruby regex string gsub string-substitution

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?

N.D。 D)和E)是我想要的输出。只是人物。

3 个答案:

答案 0 :(得分:16)

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

答案 1 :(得分:4)

我有这个

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

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

i修饰符使正则表达式独立,因此a-z也匹配A-Z。一个小的区别是这个正则表达式也将替换_,而{{1}}不会被你的。{/ p>取代

答案 2 :(得分:2)

如果您还要保留unicode字母,请使用以下字母:

/\PL/

这匹配所有非字母字符。