A shorter way to remove non-characters than gsub (/ \ d | \ W /, "")

my_string = 'Here the #: 49848! - but will dashes, commas & stars (*) show?' puts src.gsub(/\d|\W/, "") 

i.e. I can delete or ("|").

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

 src = "Here 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 the #: 49848! - but will dashes, commas & stars (*) show? B) - Here the #: ! - but will dashes, commas & stars (*) show? C) - Heresthe49848butwilldashescommasstarsshow D) - Heresthebutwilldashescommasstarsshow E) - Heresthebutwilldashescommasstarsshow F) - Here the #: 49848! - but will dashes, commas & stars (*) show? 

nd D) and E) is what I want for output. Just characters.

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

I have this one

 src.gsub(/[^az]/i, "") 

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

The i modifier makes the regex case independent, so az also matches az . The slight difference is that this regular expression will also replace _ , which will not be replaced by yours.

+4
source

If you want to save Unicode letters, use the following:

 /\PL/ 

This matches all characters without a letter.

+2
source

Source: https://habr.com/ru/post/1394484/


All Articles