RE: Optimal Regex?

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

 



> Wow, that definitely works. I would sort of like to know how to tweak the
regex, but maybe this is the best way of doing it. Is "[0-9]*[.0-9]*?" the
best way of looking for a number with decimals?

Hi David,

Just to answer this question, I would probably use something like the
following pattern to match a number with optional decimals:

-?([\d]+)?(\.[\d]+)?

In and of itself, the pattern you have above will only match numeric digits.
So, with a string of "23.99", it would match the "23" and the "99" as
separate matches. Basically this happens because you have the 'lazy'
quantifier (ie "?") after the zero-or-more-occurrences quantifier ("*"), and
the laziest iteration of "[.0-9]*?" is to match nothing.

A small improvement can be made by putting () around the [.0-9]* part of the
pattern, thus: ([.0-9]*)?

This now becomes the "optional quantifier", indicating that the pattern
between () can be matched *if it exists*.

This still isn't perfect, however, since the modified "[0-9]*([.0-9]*)?"
will not only match a number like "29.33" in it's entirety, it will also
match "129..3..57" in its entirety. This is because you include the period
(".") within the character class, so it can be matched zero-or-more times as
well as the digits. Moving the period (".") outside the character class so
that the regex only attempts to find an optional single instance of it
between two sets of numbers (where the second set of numbers is also
optional) makes another improvement.

"[0-9]*(\.[0-9]*)?"

Note that I've escaped the period, because otherwise it would be interpreted
as meaning "any single character".

This should now work pretty much as you expect it to.

My version adds the ability to match both positive and negative numbers with
decimals. It also uses the shorthand character class for numeric digits
("\d").

Hope this is of some help.

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