「Java」正規表現($)で終わる文字列を判定するサンプル
説明
行末 $
「ed$」は「ed」で終わる文字列
Javaコード
package com.arkgame.study;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class SekiHoDemo {
// 「ark」で終わる文字列
public static final String regPt = "ark$";
public static void main(String[] args) {
String strA = "123ARK";
String strB = "game123ark";
// 大文字小文字無視
Pattern pt = Pattern.compile(regPt, Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
if (testFunc(pt, strA) == true) {
System.out.println("文字列A「 " + strA + "」が「ark」で終わる文字列");
} else {
System.out.println("文字列A「" + strA + "」が「ark」で終わる文字列ではない");
}
if (testFunc(pt, strB) == true) {
System.out.println("文字列B「" + strB + "」が「ark」で終わる文字列");
} else {
System.out.println("文字列B「" + strB + "」が「ark」で終わる文字列ではない");
}
}
public static boolean testFunc(Pattern pattern, String target) {
// 正規表現判定
Matcher mt = pattern.matcher(target);
return mt.find();
}
}
package com.arkgame.study;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class SekiHoDemo {
// 「ark」で終わる文字列
public static final String regPt = "ark$";
public static void main(String[] args) {
String strA = "123ARK";
String strB = "game123ark";
// 大文字小文字無視
Pattern pt = Pattern.compile(regPt, Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
if (testFunc(pt, strA) == true) {
System.out.println("文字列A「 " + strA + "」が「ark」で終わる文字列");
} else {
System.out.println("文字列A「" + strA + "」が「ark」で終わる文字列ではない");
}
if (testFunc(pt, strB) == true) {
System.out.println("文字列B「" + strB + "」が「ark」で終わる文字列");
} else {
System.out.println("文字列B「" + strB + "」が「ark」で終わる文字列ではない");
}
}
public static boolean testFunc(Pattern pattern, String target) {
// 正規表現判定
Matcher mt = pattern.matcher(target);
return mt.find();
}
}
package com.arkgame.study; import java.util.regex.Matcher; import java.util.regex.Pattern; public class SekiHoDemo { // 「ark」で終わる文字列 public static final String regPt = "ark$"; public static void main(String[] args) { String strA = "123ARK"; String strB = "game123ark"; // 大文字小文字無視 Pattern pt = Pattern.compile(regPt, Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE); if (testFunc(pt, strA) == true) { System.out.println("文字列A「 " + strA + "」が「ark」で終わる文字列"); } else { System.out.println("文字列A「" + strA + "」が「ark」で終わる文字列ではない"); } if (testFunc(pt, strB) == true) { System.out.println("文字列B「" + strB + "」が「ark」で終わる文字列"); } else { System.out.println("文字列B「" + strB + "」が「ark」で終わる文字列ではない"); } } public static boolean testFunc(Pattern pattern, String target) { // 正規表現判定 Matcher mt = pattern.matcher(target); return mt.find(); } }
結果
文字列A「 123ARK」が「ark」で終わる文字列
文字列B「game123ark」が「ark」で終わる文字列