[JAVA] Distinguish between integers and decimals with regular expressions

A memorandum when judging integers and decimals of character strings in Java

Thing you want to do

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.

Prerequisites

jdk1.8.0_40

result

^-?(0|[1-9]\d*)(\.\d+|)$

test

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

Distinguish between integers and decimals with regular expressions
Switch beans with @ConditionalOnExpression and SpEL regular expressions
colorize and regular expressions
Parse Japanese addresses with regular expressions
Regular expressions
Easily make troublesome regular expressions with Rubular
Distinguish between runtime and compile time polymorphism
Easy to trip with Java regular expressions
Distinguish between positive and negative numbers in Java
[Swift] About the inability to distinguish between full-width and half-width characters with NS Predicate
[RSpec] WebMock handles regular expressions and Array query strings
Arbitrate the fight between PowerMock and jacoco with Gradle