A memorandum when judging integers and decimals of character strings in Java
I want to treat a character string consisting of only numbers and decimal points as positive. (Excluding exponential notation)
With the Double.parsedouble (str) method, the exponential notation `2.4e + 8```,
`NaN, and
Infinity``` will be parsed, so use a regular expression. I made a judgment.
jdk1.8.0_40
^-?(0|[1-9]\d*)(\.\d+|)$
Test code
List<String> targets = Arrays.asList("0","-0","0.8","0.878","1","-1","1.1",
"1.123","544","42.195","000","000.0","2.4e+8","3.1e-2","-6.75e-7",
"0X02.Bp-1","1.","155.","000.0","-0.","-0000.","0x07","A","1",
"-","NaN","Infinity","-Infinity");
String regex = "^-?(0|[1-9]\\d*)(\\.\\d+|)$";
Pattern p = Pattern.compile(regex);
for(String s : targets){
Matcher matcher = p.matcher(s);
if(matcher.matches())
System.out.println("match! : " + s);
else
System.out.println("Not applicable: " + s);
}
The test target is suitable.
result
match! : 0
match! : -0
match! : 0.8
match! : 0.878
match! : 1
match! : -1
match! : 1.1
match! : 1.123
match! : 544
match! : 42.195
Not applicable: 000
Not applicable: 000.0
Not applicable: 2.4e+8
Not applicable: 3.1e-2
Not applicable: -6.75e-7
Not applicable: 0X02.Bp-1
Not applicable: 1.
Not applicable: 155.
Not applicable: 000.0
Not applicable: -0.
Not applicable: -0000.
Not applicable: 0x07
Not applicable: A
Not applicable: 1
Not applicable: -
Not applicable: NaN
Not applicable: Infinity
Not applicable: -Infinity
Recommended Posts