4

I am searching for a regular expression that matches any string that is:

  1. A number which is greater than zero
  2. The number has at least one digit
  3. No more than 12 digits

I tried this one without success:

^[1-9][0-9]*{1,12}$ 
2
  • Can you have numbers that contain leading zeros but are greater than zero? Commented Oct 27, 2016 at 7:53
  • @SebastianProske Would be nice but does not have to be like that. Interesting point! Commented Oct 27, 2016 at 8:09

4 Answers 4

8

If numbers with leading zeros that are greater than zero are allowed, you can use ^(?!0+$)[0-9]{1,12}$ if the tool/language you use supports lookaheads. The lookahead is used to ensure that the number doesn't entirely consist of zeros.

Sign up to request clarification or add additional context in comments.

Comments

3

The problem with the regular expression

 ^[1-9][0-9]*{1,12}$ 

is the star * used together with {1,12} as the star *means any number of repetitions of the previous symbol whereas {1,12} means one to twelve repetitions - so the star * and {a,b} don't mix and must be used exclusively, not together.

Comments

3

Use ^[1-9]\d{0,11}$, which checks for a non-zero digit followed by zero to 11 digits.

Your regex had a quantifier * after the second character class, which would allow zero or more occurrence of a digit (which can be more than 11 digits). Also the quantifier {1,12} sets the minimum occurrence of preceding pattern as 1 and maximum occurrence as 12. So you had to avoid the * and set minimum and maximum as 0 and 11 respectively, since there was already a pattern for single digit.

Comments

2

^[1-9][0-9]{0,11}$

Start with a single digit between 1-9, then have 0 to 11 occurrences of a digit between 0-9

2 Comments

Why do you have a capture group around the last 0-11 digits?
You're right, my mistake. I was testing something else with this expression and forgot to remove the group. Updated now!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.