Java11 Patternクラスを使って英字のチェックを実装するサンプル

環境
Java SE 11
Eclipse 4.26.0

構文
Pattern 変数名 = Pattern.compile(“^[a-zA-Z]+$");
変数名.matcher(対象文字列).matches();
Patternクラスを使って、引数の値が英字の正規表現に一致するか確認します。
英字の場合、trueを返します。英字ではない場合、falseを返します

正規表現式

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
英字      ^[a-zA-Z]+$
英字(大文字) ^[A-Z]+$
英字(小文字) ^[a-z]+$
英字      ^[a-zA-Z]+$ 英字(大文字) ^[A-Z]+$ 英字(小文字) ^[a-z]+$
英字      ^[a-zA-Z]+$
英字(大文字) ^[A-Z]+$
英字(小文字) ^[a-z]+$

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
package com.arkgame.study;
import java.util.regex.Pattern;
public class ArktestDemo {
public static void main(String[] args) {
System.out.println("英字(小文字)のチェック結果:" + isFun("study"));
System.out.println("英字(大文字)のチェック結果:" + isFun("ARKGAME"));
System.out.println("数字のチェック結果:" + isFun("202321"));
}
/**
* 英字のチェック
* @param target
* @return 英字true 英字ではないfalse
*/
public static boolean isFun(String target) {
boolean res = false;
if (target != null) {
Pattern pattern = Pattern.compile("^[a-zA-Z]+$");
res = pattern.matcher(target).matches();
}
return res;
}
}
package com.arkgame.study; import java.util.regex.Pattern; public class ArktestDemo { public static void main(String[] args) { System.out.println("英字(小文字)のチェック結果:" + isFun("study")); System.out.println("英字(大文字)のチェック結果:" + isFun("ARKGAME")); System.out.println("数字のチェック結果:" + isFun("202321")); } /** * 英字のチェック * @param target * @return 英字true 英字ではないfalse */ public static boolean isFun(String target) { boolean res = false; if (target != null) { Pattern pattern = Pattern.compile("^[a-zA-Z]+$"); res = pattern.matcher(target).matches(); } return res; } }
package com.arkgame.study;

import java.util.regex.Pattern;

public class ArktestDemo {

      public static void main(String[] args) {
            System.out.println("英字(小文字)のチェック結果:" + isFun("study"));
            System.out.println("英字(大文字)のチェック結果:" + isFun("ARKGAME"));
            System.out.println("数字のチェック結果:" + isFun("202321"));

      }

      /**
       * 英字のチェック 
       * @param target
       * @return 英字true 英字ではないfalse
       */
      public static boolean isFun(String target) {
            boolean res = false;
            if (target != null) {
                  Pattern pattern = Pattern.compile("^[a-zA-Z]+$");
                  res = pattern.matcher(target).matches();
            }
            return res;
      }
}

実行結果
英字(小文字)のチェック結果:true
英字(大文字)のチェック結果:true
数字のチェック結果:false

Java

Posted by arkgame