hi I found on the Internet that this regexp accept positive number ^\d+$ a开发者_JS百科nd 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
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!
Try ^[0-9]*$
. This one allows numbers and nothing.
How about ^\d*$
? That would accept a sequence of digits (i.e. a positive integer) by itself in a line without whitespace or an empty line.
精彩评论