「java」matches()で文字列と指定正規表現に一致するかどうかを判定する

書式
public boolean matches(String regex)
この文字列が、指定された正規表現と一致するかどうかを判定します。
使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
package com.arkgame.study.tm;
public class MatchDemo {
private static final String ptn = "[1-6]";
public static void main(String[] args) {
String strA = "3";
String strB = "a123";
func(strA);
func(strB);
}
public static void func(String str) {
if (str.matches(ptn)) {
System.out.println("message A: match result");
} else {
System.out.println("message B: not match result");
}
}
}
package com.arkgame.study.tm; public class MatchDemo { private static final String ptn = "[1-6]"; public static void main(String[] args) { String strA = "3"; String strB = "a123"; func(strA); func(strB); } public static void func(String str) { if (str.matches(ptn)) { System.out.println("message A: match result"); } else { System.out.println("message B: not match result"); } } }
package com.arkgame.study.tm;

public class MatchDemo {

      private static final String ptn = "[1-6]";

      public static void main(String[] args) {
            String strA = "3";
            String strB = "a123";
            func(strA);
            func(strB);

      }

      public static void func(String str) {
            if (str.matches(ptn)) {
                  System.out.println("message A: match result");
            } else {
                  System.out.println("message B: not match result");
            }

      }

}

実行結果
message A: match result
message B: not match result

Java

Posted by arkgame