「Java」PatternとMatcherで半角数字を判断する

2021年9月30日

構文
1.public static Pattern compile(String regex)
指定された正規表現をパターンにコンパイルします。
2.public Matcher matcher(CharSequence input)
指定された入力とこのパターンをマッチする正規表現エンジンを作成します。

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
package com.arkgame.bat;
import java.util.regex.Pattern;
public class EsampDemo {
/** 半角数字の正規表現 */
private static final Pattern ALP_UPPER = Pattern.compile("\\d+");
public static void main(String[] args) {
// 小文字 半角数字
String strA = "study345";
// 大文字 全角数字
String strB = "345テスト";
// 小文字大文字混在
String strC = "Com";
// 関数を呼び出す
checkfunc(strA);
checkfunc(strB);
checkfunc(strC);
}
public static void checkfunc(String target) {
// 指定された入力とこのパターンをマッチする正規表現エンジンを作成します
if (ALP_UPPER.matcher(target).find()) {
System.out.println(target + " 半角数字に含まれる");
} else {
System.out.println(target + " 半角数字に含まれない");
}
}
}
package com.arkgame.bat; import java.util.regex.Pattern; public class EsampDemo { /** 半角数字の正規表現 */ private static final Pattern ALP_UPPER = Pattern.compile("\\d+"); public static void main(String[] args) { // 小文字 半角数字 String strA = "study345"; // 大文字 全角数字 String strB = "345テスト"; // 小文字大文字混在 String strC = "Com"; // 関数を呼び出す checkfunc(strA); checkfunc(strB); checkfunc(strC); } public static void checkfunc(String target) { // 指定された入力とこのパターンをマッチする正規表現エンジンを作成します if (ALP_UPPER.matcher(target).find()) { System.out.println(target + " 半角数字に含まれる"); } else { System.out.println(target + " 半角数字に含まれない"); } } }
package com.arkgame.bat;

import java.util.regex.Pattern;

public class EsampDemo {

      /** 半角数字の正規表現 */
      private static final Pattern ALP_UPPER = Pattern.compile("\\d+");

      public static void main(String[] args) {
            // 小文字 半角数字
            String strA = "study345";
            // 大文字 全角数字
            String strB = "345テスト";
            // 小文字大文字混在
            String strC = "Com";

            // 関数を呼び出す
            checkfunc(strA);
            checkfunc(strB);
            checkfunc(strC);
      }

      public static void checkfunc(String target) {
            // 指定された入力とこのパターンをマッチする正規表現エンジンを作成します
            if (ALP_UPPER.matcher(target).find()) {
                  System.out.println(target + " 半角数字に含まれる");
            } else {
                  System.out.println(target + " 半角数字に含まれない");
            }

      }

}

実行結果
study345 半角数字に含まれる
345テスト 半角数字に含まれない
Com 半角数字に含まれない

Java

Posted by arkgame