From: "Jason D. Clinton" Date: 2006-06-29T02:14:16+09:00 Subject: Re: remove all illegal chars form string --=-HdN8U/UDiOdK1Bn5vKK0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: quoted-printable On Wed, 2006-06-28 at 22:09 +0900, thomas coopman wrote: > 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|=C2=A7" --> "exampLe" >=20 > 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. An except from my upcoming book, Ruby Phrasebook: """ new_password =3D gets if new_password.count '^A-Za-z._' !=3D 0 then puts "Bad Password" else #do something end This works by using a special syntax that's shared by .count, .tr, delete, and squeeze. A parameter beginning with ^ negates the list; the list consists of any valid characters in the active character set and may contain ranges formed with -. If more than one parameter list is given to these functions, the lists of characters are intersected using set logic[md]that is, only characters in both lists are used for filtering. You might also want to simply replace all "evil" characters with _ (such as perhaps from a CGI form post): evil_input =3D '`cat /etc/passwd`'=20 evil_input.tr('./\`', '_') #=3D> "_cat _etc_passwd_" """ In your specific question, you will want to use .delete: 'exam@p Le3|=C2=A7'.delete '^A-Za-z' #=3D> "exampLe" --=-HdN8U/UDiOdK1Bn5vKK0 Content-Type: application/pgp-signature; name=signature.asc Content-Description: This is a digitally signed message part -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.3 (GNU/Linux) iD8DBQBEopdotSqjk42zvwkRAuvSAKCwr2yIpsj9q5dnUm8xhu+ZFUrFwgCfcbLE 4RfRlK7kGae/tbe7EhO2SdU= =CfA1 -----END PGP SIGNATURE----- --=-HdN8U/UDiOdK1Bn5vKK0--