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

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

つまり、or ("|") を削除できますか。

これが私がここにたどり着いた方法です、私は短くできますか?

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 に答える