Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex which accept positive integer and nothing

Tags:

java

regex

hi I found on the Internet that this regexp accept positive number ^\d+$ and this accept nothing ^$ So no I wanna combine this two regexp but with no success. I try this (^\d+$)|(^$) but this didnt work. So help me with regexp which accept positive integer and nothing thx a lot

like image 971
hudi Avatar asked Nov 17 '25 23:11

hudi


2 Answers

Simply do:

^\d*$

The * means: "zero or more times".

Since you've asked most questions with the Java tag, I'm assuming you're looking for a Java solution. Note that inside a string literal, the \ needs to be escaped!

A demo:

class Test {
  public static void main(String[] args) {
    String[] tests = {"-100", "", "2334", "0"};
    for(String t : tests) {
      System.out.println(t + " -> " + t.matches("\\d*"));
    }
  }
}

produces:

-100 -> false
 -> true
2334 -> true
0 -> true

Note that matches(...) already validates the entire input string, so there's no need to "anchor" it with ^ and $.

Beware that it would also return true for numbers that exceed Integer.MAX_VALUE and Long.MAX_VALUE. SO even if matches(...) returned true, parseInt(...) or parseLong(...) may throw an exception!

like image 124
Bart Kiers Avatar answered Nov 19 '25 12:11

Bart Kiers


Try ^[0-9]*$ . This one allows numbers and nothing.

like image 30
Marek Musielak Avatar answered Nov 19 '25 14:11

Marek Musielak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!