Fedreg
Fedreg

Reputation: 581

Regex for numbers 1-25

I am working on a music generation project. Input only contains alpha characters and digits. The regex is one of the requirements we've set as a limitation.

So, this gets me numbers under 26 but if a number like 27 shows up it still picks up the 2 and the 7. How can I exclude all numbers 26 and up? Thanks!

/[0-2][0-5]|[1-9]/g 

I should add...this is part of a large string with letters and spaces before and after the numbers. So I have to recognize the numbers in the string and pull them out. Only using string.prototype.match() and regex. Long story. Thx

Upvotes: 2

Views: 18933

Answers (4)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627101

Your [0-2][0-5]|[1-9] regex pattern matches any sequence of a 0-2 digit followed with 0-5 digit OR a 1-9 digit anywhere inside the string.

To match individual values from 1 till 25, you may use

/\b(0?[1-9]|1[0-9]|2[0-5])\b/g

See the regex demo

Pattern details:

  • \b - leading word boundary
  • (0?[1-9]|1[0-9]|2[0-5]) - either of the alternatives:
    • 0?[1-9] - an optional leading 0 followed with a digit from 1 to 9
    • 1[0-9] - 10 till 19
    • 2[0-5] - 20 till 25
  • \b - trailing word boundary

Upvotes: 3

Steve Kline
Steve Kline

Reputation: 805

Ahh... so you have right now... 0-5, 10-15, 20-25 OR 0-9

You had the right idea, just wrong application of the idea.

([01]?[0-9]|2[0-5])

// should omit those pesky one-offs you're seeing as mentioned in the comments.
^([01]?[0-9]|2[0-5])$
\b([01]?[0-9]|2[0-5])\b

// if you also want to exclude 0...
^([1-9]|1[0-9]|2[0-5])$
\b([1-9]|1[0-9]|2[0-5])\b

That figuratively says any number between 0 thru 19(w/ or w/o preleading 0's) OR 20-25.

Upvotes: 2

rockerest
rockerest

Reputation: 10518

^\d$|^1\d$|^2[0-6]$ will match 0-26.

However, this is not a problem you should be solving with regex. A better solution is to test the number with operators like < or <=:

myNum < 27 // is 0-26

Upvotes: 0

piet.t
piet.t

Reputation: 11911

I would suggest something along the lines of (take or remove some of the elements I added as I don't know your exact requirements)

/^(([ 01]?[1-9])|2[0-5])$/
  • The ^...$ to match the entire input to avoid matching single digits of a two-digit input
  • ? to allow for a one-digit input
  • the | to allow for the two cases "first digit = 0 or 1" and "first digit = 2"

But over all there certainly are better tools than regex to do this job, like parsing the number and doing a simple comparison.

Upvotes: 0

Related Questions