[thelist] numeric only regex?

Frank lists at frankmarion.com
Tue Aug 2 20:12:36 CDT 2005


At 12:51 PM 2005-08-02, you wrote:
>Hi, I'm trying to come up with a simple regex that will allow me to test 
>for numbers 0-9 ONLY. The
>numbers are held in a variable 'numtext'. I got as far as:
>
>var match = /[\d\d]/.test(numtext);

I need to clarify something:

Are you saying that you want 1 to infinity digits to return true 
exclusively? That any character other than a digit should return false? 
Then you could do:

^[0-9]*$

Match: start of string, [digits only] zero or more times, end of string.

Try this, then insert some other chars.


var chars = "123"
if (chars.match(/^[0-9]*$/)) {
          alert("string has only digits");
} else {
         alert("string has bad chars");
}

The thing about regex that makes it hard to grok sometimes is that regex is 
a patter MATCHING language, not a procedural language.  It searches for 
matches exclusively, so you have to think "only what is there". It's a 
great mind twister. I love it.

By the way, what's the context of this? Sometimes it helps if we know what 
you are wanting to do. Sometimes regex is only one way to go.




Frank Marion     lists at frankmarion.com      Keep the signal high.




-- 
No virus found in this outgoing message.
Checked by AVG Anti-Virus.
Version: 7.0.338 / Virus Database: 267.9.7/60 - Release Date: 2005-07-28




More information about the thelist mailing list