5
5

More than 5 years have passed since last update.

正規表現で整数と小数を判別する

Posted at

Javaで文字列の整数・小数判定を行った際の備忘録

やりたいこと

数字と小数点のみで構成されている文字列を正として扱いたい。(指数表記等を除く)
Double.parsedouble(str)メソッドだと、指数表記である2.4e+8NaNInfinityがパースされてしまうため、正規表現で判別を行いました。

前提条件

jdk1.8.0_40

結果

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

テスト

テストコード
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("対象外 : " + s);
}

テスト対象は適当です。

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
対象外 : 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
5
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5