|
Posted by "Mark Rees" on 09/08/05 11:17
""Murray @ PlanetThoughtful"" <lists@planetthoughtful.org> wrote in message
news:7A.95.23233.1F00F134@pb1.pair.com...
> > Hi all,
> >
> >
> > I want to write regular expression for checking the string format
entered
> > by user.
> >
> > the allowed formats are
> >
> > examples:
> > 10
> > 10,
> > 10,12-10
> > 12-10
> >
> > that is the valid strings are:
> > 1. only integer
> > 2. an integer, range of integers example 3
> >
> > and no other characters must be allowed.
You could simplify the matter by replacing all "-" and "," with, say, 0 and
then using the simple "\d+" (I think) regexp.
>
> Hi babu,
>
> As you've pointed out, you have 4 distinct scenarios to deal with, and it
> may be very difficult, without a great deal of tuning and tweaking, to
> define a regular expression that can effectively match all 4 scenarios
> without including false matches as well.
>
> One way of dealing with this is to build more specialized and exact
regular
> expressions for each possible scenario and group them together in an if
> statement.
>
> Eg.
>
> if (preg_match('/^\d+$/',$subject) || preg_match('/^\d+,$/',$subject) ||
> preg_match('/^\d+,\d+-\d+$/', $subject) || <etc etc>){
>
> // code for successful match of valid data in $subject
>
> } else {
>
> // code for invalid data in $subject
>
> }
>
> Basically, the if/else statement is testing each distinct possible pattern
> and executing code if any of those distinct possible patterns match.
>
> It may not ultimately be the most graceful way of dealing with the
> situation, but having spent many hours attempting to tweak complex regular
> expressions looking for the magic combination, I've learned that breaking
> scenarios down this way can save a lot of development time and
frustration.
> This doesn't mean there isn't a benefit to finding the perfect regular
> expression for your needs, just that it can often be difficult to
guarantee
> your code won't be plagued by false matches or false exclusions as your
> expression becomes more and more complex.
>
> Hope this helps a little.
>
> Much warmth,
>
> Murray
> ---
> "Lost in thought..."
> http://www.planetthoughtful.org
Navigation:
[Reply to this message]
|