From: Matthew Smillie Date: 2006-06-29T02:12:15+09:00 Subject: Re: remove all illegal chars form string On Jun 28, 2006, at 14:09, thomas coopman wrote: > Hi, > > Is there a simple way to remove all but the legal chars from a > string. where the legal chars are for example: a-z A-Z 0-9 > So everything should be removed from the string but these characters. > "exam@p Le3|�" --> "exampLe" > > I don't know very much about regular expressions, so I don't know > if it's possible with sub or gsub. My first Idea was to loop over > the string and check every character but I wondered if there is > something more simple or better. > > Thanks It's dead easy: test = "exam@p Le3|�" test.gsub(/[^A-Za-z0-9]/, '') => "exampLe3" Quick explanation: [] defines a group you want to treat as one character. If you only wanted vowels, ferinstance, you'd use [aeiou]. ^ as the first character in a group means the opposite of that group. Everything that isn't a vowel would be like this: [^aeiou] A-Z is a range of characters, and you can do smaller ranges like c-q or whatever, the ordering used to determine the range is the character encoding. This means you can just say A-z in place of A-Za- z (at least in ASCII and compatible encodings - I don't know about anything else), but I think that tends to make things a little less clear, especially since a-Z is invalid because a > Z in ASCII. There are also shortcuts for some classes of characters, \d is equivalent to [0-9], and \w is close to [A-z0-9] but also includes the underscore character '_'. So the regular expression says 'match any single character that is not in the ranges A-Z, a-z, or 0-9'. #gsub takes everything matched by the regular expression, and replaces it with nothing. matthew smillie.