Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One or two numeric digits Regex

I have the below code. It works only when I have 2 digits. If I have 1 digit doesn't work. I want to work in both cases: one or two digit.
var numberRegex = /^[1-9][0-9]$/;
I've tried something like this but unfortunately doesn't work:
var numberRegex = /^[1-9]?[1-9][0-9]$/;
Thanks for support.

like image 766
CBuzatu Avatar asked May 27 '12 02:05

CBuzatu


People also ask

Which regex matches one or more digits?

Occurrence Indicators (or Repetition Operators): +: one or more ( 1+ ), e.g., [0-9]+ matches one or more digits such as '123' , '000' . *: zero or more ( 0+ ), e.g., [0-9]* matches zero or more digits. It accepts all those in [0-9]+ plus the empty string.

What would be a regex expression that would find all 2 digit numbers?

To match a two digit number / \d{2} / is used where {} is a quantifier and 2 means match two times or simply a two digit number. Similarly / \d{3} / is used to match a three digit number and so on.

How do I match a number in regex?

The regex [0-9] matches single-digit numbers 0 to 9. [1-9][0-9] matches double-digit numbers 10 to 99. That's the easy part. Matching the three-digit numbers is a little more complicated, since we need to exclude numbers 256 through 999.


2 Answers

Try this one out:

/^\d{1,2}$/;

Reading what you have it looks like you don't want to accept numbers like 01.

/^\d{1}|[1-9]\d{1}$/;
like image 167
Joel Etherton Avatar answered Sep 22 '22 17:09

Joel Etherton


Try this.

/^[0-9]|[0-9][0-9]$/

This should do the job. Using an Or operator does it.

like image 30
Vishak Kavalur Avatar answered Sep 22 '22 17:09

Vishak Kavalur