Page 1 of 1

Regex Question

Posted: Fri Apr 30, 2010 7:54 pm
by JakeJ
I suck at regex. I'm using a form validator and I need to test for just one or more zeros. It can have a zero along with other numbers and a decimal (I've got that worked out), but how do I test for only one or more zeros?

Thanks ahead of time. I really need to learn more regex stuff.

Re: Regex Question

Posted: Fri Apr 30, 2010 9:51 pm
by s.dot
+ quantifier = 1 or more times

Code: Select all

$str = '000000';
if (preg_match('/0+/', $str))
{
   echo 'found one or more zeros!';
}
Moved to regex

Re: Regex Question

Posted: Fri Apr 30, 2010 10:11 pm
by ridgerunner
If you want to find only zeroes, you need to add anchors to match the beginning ^ and end $ of the string like so:

Code: Select all

$str = '000000';
if (preg_match('/^0+$/', $str))
{
   echo 'found only one or more zeros!';
}
:)

Re: Regex Question

Posted: Fri Apr 30, 2010 10:32 pm
by JakeJ
Thanks Ridgerunner, I appreciate the help.

Re: Regex Question

Posted: Mon May 03, 2010 5:42 am
by JakeJ
Ok, so it turns out I needed to test that it is NOT just all zeros. So I came up with "/[^0+$]/" which works fine.

BUT.. I realized that expression doesn't test for 0.00 which is also invalid. So I came up with "/[^0+$].[^0+$]/" and I thought that was working. It allows 101 but not 10000. Why? I don't quite understand.

I'll leave off checking for a decimal point for now. Please advise. Thanks!

Re: Regex Question

Posted: Mon May 03, 2010 9:05 am
by ridgerunner
JakeJ wrote:Ok, so it turns out I needed to test that it is NOT just all zeros. So I came up with "/[^0+$]/" which works fine.

BUT.. I realized that expression doesn't test for 0.00 which is also invalid. So I came up with "/[^0+$].[^0+$]/" and I thought that was working. It allows 101 but not 10000. Why? I don't quite understand.

I'll leave off checking for a decimal point for now. Please advise. Thanks!
Whoah! Can't use a character class like that!
This regex...
[text]/[^0+$]/[/text]
Means: Match one character that is not a zero or a plus or a dollar sign.

A character class (anything between the square brackets) always matches exactly one character (and one character only). Go spend an hour at the following tutorial. You'll thank me later...
http://www.regular-expressions.info/quickstart.html

There are several ways to accomplish what you want. Here is one way:

Code: Select all

if (preg_match('/^(?![0.]+$)/', $contents)) {
    # String is not a bunch of zeros and decimal points
} else {
    # String is a bunch of zeros and decimal points
}

Re: Regex Question

Posted: Mon May 03, 2010 11:56 am
by JakeJ
That works perfectly, thanks!

And I'll go through that tutorial, I really need to learn regex.