From: Robert Klemme Date: 2008-05-14T01:45:07+09:00 Subject: Re: detail on a regex? On 13.05.2008 17:59, Kyle Schmitt wrote: > Is there a way to pull details out of a regular expression's failure? > > I'm running into a situation where I've got some validation methods, > and I'm resorting to passing in both a regular expression and a range. > I know quite well I could just use a range inside of a regex, and > would rather, but I need to get the range in order to have some useful > error messages. > > For example, the string must be 3 to 8 characters long, start with a > letter, and may contain letters numbers or dashes. > > I would like to just use this: > some_string=~/^[a-z][-a-z0-9]{2,7}$/i > > But if the match fails, I can't give out any good error messages > without further inspecting the string, so I end up with > some_string=~/^[a-z][-a-z0-9]$/i > [3..8].include?some_string.length > > Just so I can give reasonable error messages. If it does not match you get no information out of the regexp. The simplest would be to just include the string in an error message. To avoid ugly errors with lengthy strings you could add a length check before the regexp match. In some cases it might be possible to build the regexp so that it matches chunks: some_string=~/^([a-z])?([-a-z0-9]{2,7})?(.*)$/i Now you have a match if $1 and $2 are non nil and $3 is empty. HTH robert