「Java」正規表現で数字以外を除くサンプル

2020年11月10日

説明
1.public boolean matches(String regex)
この文字列が、指定された正規表現と一致するかどうかを判定します。
2.public static Integer valueOf(String s) throws NumberFormatException
指定されたStringの値を保持するIntegerオブジェクトを返します。
Javaコード

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
package com.arkgame.study.it;
public class ShuziDemo {
private static String ptn = "^[0-9]+$";
public static void main(String[] args) {
String strA = "";
String strB = "2020";
String strC = "ab202";
System.out.println("文字列Aの値の変換結果:" + func(strA));
System.out.println("文字列Bの値の変換結果:" + func(strB));
System.out.println("文字列Cの値の変換結果:" + func(strC));
}
//数字のみ
public static int func(String target) {
int result = 0;
//正規表現
if (!"".equals(target) && target.matches(ptn)) {
result = Integer.valueOf(target);
}
return result;
}
}
package com.arkgame.study.it; public class ShuziDemo { private static String ptn = "^[0-9]+$"; public static void main(String[] args) { String strA = ""; String strB = "2020"; String strC = "ab202"; System.out.println("文字列Aの値の変換結果:" + func(strA)); System.out.println("文字列Bの値の変換結果:" + func(strB)); System.out.println("文字列Cの値の変換結果:" + func(strC)); } //数字のみ public static int func(String target) { int result = 0; //正規表現 if (!"".equals(target) && target.matches(ptn)) { result = Integer.valueOf(target); } return result; } }
package com.arkgame.study.it;

public class ShuziDemo {

      private static String ptn = "^[0-9]+$";

      public static void main(String[] args) {

            String strA = "";
            String strB = "2020";
            String strC = "ab202";

            System.out.println("文字列Aの値の変換結果:" + func(strA));
            System.out.println("文字列Bの値の変換結果:" + func(strB));
            System.out.println("文字列Cの値の変換結果:" + func(strC));

      }

      //数字のみ
      public static int func(String target) {
            int result = 0;
            //正規表現
            if (!"".equals(target) && target.matches(ptn)) {
                  result = Integer.valueOf(target);
            }
            return result;
      }
}

結果
文字列Aの値の変換結果:0
文字列Bの値の変換結果:2020
文字列Cの値の変換結果:0

Java

Posted by arkgame