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

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

i.e. can I remove the or ("|").

Here's how I got here, can I get shorter?

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) and E) are what I want for output. Just characters.

sawa
  • 165,429
  • 45
  • 277
  • 381
Michael Durrant
  • 93,410
  • 97
  • 333
  • 497

3 Answers3

19
my_string = "Here's the #: 49848! - but will dashes, commas & stars (*) show?"
p my_string.delete('^a-zA-Z')
#=>"Heresthebutwilldashescommasstarsshow"
steenslag
  • 79,051
  • 16
  • 138
  • 171
4

I have this one

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

also not shorter, but better to read in my opinion.

The i modifier makes the regex case independent, so that a-z matches also A-Z. A small difference is that this regex will also replace _ which is not replaced by yours.

stema
  • 90,351
  • 20
  • 107
  • 135
  • +1 good to know there's an underscore option as there could be cases both ways ! :) – Michael Durrant Feb 03 '12 at 04:33
  • The problem with this syntax is, it also removes 'spaces', so all the words in the sentece will be concatenated together like, 'thisismycomment' – Magesh Feb 14 '13 at 10:35
2

If you want to keep also unicode letters, use this one:

/\PL/

This matches all non letter character.

Toto
  • 89,455
  • 62
  • 89
  • 125