「Java」正規表現でパイプ記号を使ってor条件を判定するサンプル

書式
^x|y$
「xで始まる」 or 「yで終わる」
Javaコード

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import java.util.regex.Pattern;
public class SekiHDemo {
// 「testで始まる」 or 「toで終わる」
protected static final String regexPt = "^test|to$";
public static void main(String[] args) {
String targetA = "12345 to";
String targetB = "test abc122";
String targetC = "test 123 to";
Pattern p1 = Pattern.compile(regexPt);
Pattern p2 = Pattern.compile(regexPt);
Pattern p3 = Pattern.compile(regexPt);
if (p1.matcher(targetA).find()) {
System.out.println("文字列「" + targetA + "」 と正規表現式に" + regexPt + " 一致");
}
if (p2.matcher(targetB).find()) {
System.out.println("文字列「" + targetB + "」 と正規表現式に" + regexPt + " 一致");
}
if (p3.matcher(targetC).find()) {
System.out.println("文字列「" + targetC + "」 と正規表現式に" + regexPt + " 一致");
}
}
}
import java.util.regex.Pattern; public class SekiHDemo { // 「testで始まる」 or 「toで終わる」 protected static final String regexPt = "^test|to$"; public static void main(String[] args) { String targetA = "12345 to"; String targetB = "test abc122"; String targetC = "test 123 to"; Pattern p1 = Pattern.compile(regexPt); Pattern p2 = Pattern.compile(regexPt); Pattern p3 = Pattern.compile(regexPt); if (p1.matcher(targetA).find()) { System.out.println("文字列「" + targetA + "」 と正規表現式に" + regexPt + " 一致"); } if (p2.matcher(targetB).find()) { System.out.println("文字列「" + targetB + "」 と正規表現式に" + regexPt + " 一致"); } if (p3.matcher(targetC).find()) { System.out.println("文字列「" + targetC + "」 と正規表現式に" + regexPt + " 一致"); } } }
import java.util.regex.Pattern;

public class SekiHDemo {

      // 「testで始まる」 or 「toで終わる」
      protected static final String regexPt = "^test|to$";

      public static void main(String[] args) {
            String targetA = "12345 to";
            String targetB = "test abc122";
            String targetC = "test 123 to";
            Pattern p1 = Pattern.compile(regexPt);
            Pattern p2 = Pattern.compile(regexPt);
            Pattern p3 = Pattern.compile(regexPt);
            if (p1.matcher(targetA).find()) {
                  System.out.println("文字列「" + targetA + "」 と正規表現式に" + regexPt + " 一致");
            }
            if (p2.matcher(targetB).find()) {
                  System.out.println("文字列「" + targetB + "」 と正規表現式に" + regexPt + " 一致");
            }
            if (p3.matcher(targetC).find()) {
                  System.out.println("文字列「" + targetC + "」 と正規表現式に" + regexPt + " 一致");
            }
      }

}

実行結果
文字列「12345 to」 と正規表現式に^test|to$ 一致
文字列「test abc122」 と正規表現式に^test|to$ 一致
文字列「test 123 to」 と正規表現式に^test|to$ 一致

Java

Posted by arkgame