RE: regular expression for integer range

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



> 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.

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

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux