「Java」正規表現の符号(^、$)で文字列の先頭、末尾を判定するサンプル

構文
「^x」 ->xで始まる
「x$」 ->xで始まる
Javaコード

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 SekiHDemo {
// toで終わる
protected static final String regexA = "to$";
// testで始まる
protected static final String regexB = "^test";
public static void main(String[] args) {
String targetA = "12345 to";
String targetB = "test abc122";
Pattern p1 = Pattern.compile(regexA);
Pattern p2 = Pattern.compile(regexB);
if (p1.matcher(targetA).find()) {
System.out.println("文字列「" + targetA + "」" + " は toで終わる");
}
if (p2.matcher(targetB).find()) {
System.out.println("文字列「" + targetB + "」" + " は testで始まる");
}
}
}
package com.arkgame.study; import java.util.regex.Pattern; public class SekiHDemo { // toで終わる protected static final String regexA = "to$"; // testで始まる protected static final String regexB = "^test"; public static void main(String[] args) { String targetA = "12345 to"; String targetB = "test abc122"; Pattern p1 = Pattern.compile(regexA); Pattern p2 = Pattern.compile(regexB); if (p1.matcher(targetA).find()) { System.out.println("文字列「" + targetA + "」" + " は toで終わる"); } if (p2.matcher(targetB).find()) { System.out.println("文字列「" + targetB + "」" + " は testで始まる"); } } }
package com.arkgame.study;

import java.util.regex.Pattern;

public class SekiHDemo {

      // toで終わる
      protected static final String regexA = "to$";
      // testで始まる
      protected static final String regexB = "^test";

      public static void main(String[] args) {
            String targetA = "12345 to";
            String targetB = "test abc122";
            Pattern p1 = Pattern.compile(regexA);
            Pattern p2 = Pattern.compile(regexB);
            if (p1.matcher(targetA).find()) {
                  System.out.println("文字列「" + targetA + "」" + " は toで終わる");
            }
            if (p2.matcher(targetB).find()) {
                  System.out.println("文字列「" + targetB + "」" + " は testで始まる");
            }
      }

}

結果
文字列「12345 to」 は toで終わる
文字列「test abc122」 は testで始まる

Java

Posted by arkgame