From: Robert Klemme Date: 2009-01-07T15:55:46+09:00 Subject: Re: Simple Regexp help On 07.01.2009 01:17, Tim Greer wrote: > Joe Blow wrote: > >> How can I test a word to make sure it ONLY contains certain >> characters? >> >> Say i have an expression like /[A-Z]/i >> >> How could i have "Testing" pass but "Testing123" fail? >> >> PS. I can not dynamically create the expression so it looks like this >> /[A-Z{10}]/ > > If you only want a-z, set the character class to start and end the > string, otherwise it'll match anything with a character that's in the > alphabet, regardless of what follows it. I.e., /^[a-z]+$/i will only > match a-z characters from start to end. Note, this is not totally safe: irb(main):001:0> s = "foo\n" => "foo\n" irb(main):002:0> /^[a-z]+$/i =~ s => 0 As you can see, even a string with a newline at the end passes. This version is safer because anchors do actually use start and end of the string: irb(main):003:0> /\A[a-z]+\z/i =~ s => nil > You can then change the > character class to whatever you wish. ^ is the start of the string and > $ is the end of the string. Actually ^ is a line start and $ is a line end (see above). For proper anchoring string start and end you need \A and \z. > + is one or more characters, so ^[a-z]+$ is > one of more characters in the character class [], being a-z, and noting > else. Note also that, depending on definition of legal string the expression should probably contain * instead of + because also the empty string does not contain any illegal characters. Kind regards robert -- remember.guy do |as, often| as.you_can - without end