How to remove any non-alpha characters (a to z) from a string using gsub and RegEx

Public, Tricks, Ruby General


Created: Dec 05, 2014     Updated: Dec 05, 2014

For example, let's say that you have a method that determines if a particular word (string) is a palindrome or not. As a fringe case, what if the string happens to contain characters like . or ~ or ; or !, or any non-alpha characters (meaning a to z characters).

You can use .gsub!(/\W+/, '') on the string to remove these non- a to z characters.

Here is an example: