Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing special characters using Ruby, but not spaces

Tags:

regex

ruby

I was looking for awhile on here and didn't quite find what I needed. I am learning Ruby(1.9) and am trying to do something basic with a text file. I am trying to use RegEx's to remove non-letters, and white space that is ONLY at the beginning of the line, ignoring spaces between tokens(I am trying to count words in the file, hence when I want the spaces between words to remain).

Ex:

555 r6ub6y i7s e7a0sy... w1o2w4.

To change to:

ruby is easy... wow.

What I have so far using the command-line to test ruby rubyfile.rb < test.txt:

$stdin.each do |line|
    line.chomp!.downcase!
    line.gsub!(/[^a-zA-Z]/, "") #this takes away my spaces!
    puts line
end
like image 390
Tyler Russell Avatar asked Sep 08 '14 16:09

Tyler Russell


People also ask

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

How to remove certain characters from a string 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 is =~ 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.


1 Answers

[^a-zA-Z. ]

add a space as well.

like image 50
vks Avatar answered Oct 02 '22 17:10

vks