2

I'm trying to write a REGEX to accept only numbers between 1-100. It would be great if it accepted everything from 1 to infinity, but that's probably to complex - or impossible.

public static boolean isNumeric(String str) {
return str.matches("-?\\d+(\\.\\d+)?");
}//end boolean.
Ray Bae
  • 89
  • 1
  • 4
  • 10

3 Answers3

3

It would be great if it accepted everything from 1 to infinity, but that's probably to complex - or impossible.

How about simply "[1-9]\\d*"?

This would accept a non-zero digit followed by any sequence of digits. In other words, any positive integer.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • Quick thought, since the input is a String, it might contain a String of 0's on start, like "007", maybe a better answer would be: `0*[1-9]\\d*` – Jorge Jan 16 '14 at 20:46
3
public static boolean isNumeric(String str) throws NumberFormatException {
    int i = Integer.parseInt(str); 
    return i > 0 && i < 100; //Arbitrary numbers within range of int
}

Not using regex but this should accomplish the same thing. Turn the string into an integer, then check to see if it is in the range you want.

takendarkk
  • 3,347
  • 8
  • 25
  • 37
  • 1
    This would throw an exception if the string contains a non-numeric character. – Dodd10x Jan 16 '14 at 19:57
  • 2
    Parsing two times is not necessary, and wrap it in a try catch with the `NumberFormatException` and if at all OP wants to have infinity Integer may overflow. – RP- Jan 16 '14 at 20:01
  • Both comments are totally true, this was just a quick and dirty example to get him pointed in a direction that might help. I will edit to fix those problems soon. – takendarkk Jan 16 '14 at 20:06
1

If you want to be really thorough, you can use "-?(0|([1-9][0-9]*))\.?[0-9]*" which should give you all numbers from -infinity to +inifinity. Getting rid of the -? will give you all positive numbers. "0|(-?[1-9][0-9]*)" should give you all integers from -infinity to +infinity. "[1-9][0-9]*" will give you all integers greater than 0.

marisbest2
  • 1,346
  • 2
  • 17
  • 30
  • Do you know how to limit this to a range including negatives? For example -100 to +100? – James Mar 18 '20 at 00:02