Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting all special characters from a string - ruby

I was doing the challenges from pythonchallenge writing code in ruby, specifically this one. It contains a really long string in page source with special characters. I was trying to find a way to delete them/check for the alphabetical chars.

I tried using scan method, but I think I might not use it properly. I also tried delete! like that:

    a = "PAGE SOURCE CODE PASTED HERE"     a.delete! "!", "@"  #and so on with special chars, does not work(?)      a 

How can I do that?

Thanks

like image 460
kwoskowicz Avatar asked Jan 30 '14 01:01

kwoskowicz


People also ask

How do I remove all special characters from a string in Ruby?

In Ruby, we can permanently delete characters from a string by using the string. delete method. It returns a new string with the specified characters removed.

What does =~ mean in Ruby?

=~ is Ruby's basic pattern-matching operator. When one operand is a regular expression and the other is a string then the regular expression is used as a pattern to match against the string. (This operator is equivalently defined by Regexp and String so the order of String and Regexp do not matter.

What does .strip do in Ruby?

The . strip method removes the leading and trailing whitespace on strings, including tabs, newlines, and carriage returns ( \t , \n , \r ).


2 Answers

You can do this

a.gsub!(/[^0-9A-Za-z]/, '') 
like image 120
Alok Anand Avatar answered Sep 22 '22 01:09

Alok Anand


try with gsub

a.gsub!(/[!@%&"]/,'') 

try the regexp on rubular.com

if you want something more general you can have a string with valid chars and remove what's not in there:

a.gsub!(/[^abcdefghijklmnopqrstuvwxyz ]/,'') 
like image 20
arieljuod Avatar answered Sep 21 '22 01:09

arieljuod