user2028437
user2028437

Reputation: 13

Regex - accept only numbers between 1 and 100 (shouldnot accept anything else)

I have the regex that accept number between 1 and 100. But it accepting the special character '%'

This is the regex that I am using

^(0*100{1,1}\\.?((?<=\\.)0*)?%?$)|(^0*\\d{0,2}\\.?((?<=\\.)\\d*)?%?)$'

I dont want to accept % Can anyone please help me in fixing this.

Upvotes: 1

Views: 27325

Answers (8)

Alok Ranjan
Alok Ranjan

Reputation: 1097

Whatever others said is fine.

I am giving a complete and more precise code for the above asked question. Hope it helps.

    const onChange = (userInput) => {
    const regex = /^([1-9]|[1-9][0-9]|100)$/;
    if (userInput === "" || regex.test(userInput)) {
      console.log("valid number and in range of 1-100");
    } else {
      console.log("not a number and in range of 1-100");
    }
  };

Upvotes: 0

Harish Nayak
Harish Nayak

Reputation: 348

^(100|[1-9][0-9]?)$ This regular expression matches between 1 to 100, 100 matches exactly 100 or [1-9] matches a character in the range 1 to 9 [0-9] matches a character in the range 0 to 9 ? matches between 0 and 1 of the preceding token

and for your reference validate the regular expression combinations here https://regexr.com/

Upvotes: 0

spex
spex

Reputation: 1137

This matches only 1 to 100 inclusive:
/\b((100)|[1-9]\d?)\b/

The \b matches word boundaries. This means something like in JavaScript:
/((100)|[1-9]\d?)/.test("I have 1000 dollars");
would return true. Instead, using the word boundaries would return false.

Upvotes: 1

Rui Jarimba
Rui Jarimba

Reputation: 18084

The regular expression suggested by Ali Shah Ahmed doesn't work with 1 digit numbers, this one does:

(100)|(0*\d{1,2})

Edited: If you don't want to accept the value 0 you can use this regular expression:

(100)|[1-9]\d?

Upvotes: 7

Naveed S
Naveed S

Reputation: 5256

This allows numbers from 1 to 100:

100|[1-9]?\d

Upvotes: 0

Ali Shah Ahmed
Ali Shah Ahmed

Reputation: 3333

i believe this regex will also work, and is bit simpler than the one you mentioned.

(100)|(0*\d{1,2})

this will take care of leading zeros as well.

Upvotes: 1

Paul Alan Taylor
Paul Alan Taylor

Reputation: 10680

I would take a multi-step approach. Wouldn't try and solve this with a regex alone. The maintenance is a nightmare.

My solution:-

Use a simple regex to determine whether the value is an integer with three or less digits.

/^\d{1,3}$/

If valid, cast to a number.

Check to see that the number is <= 100 and >= 0.

Upvotes: 1

orique
orique

Reputation: 1303

Remove all the %?. This indicates that the regex should match zero or one % characters.

Upvotes: 1

Related Questions