「Java」文字列から正規表現ですべての文字を抽出する方法

テスト用プログラム:
public static void myTest() {
String testStr = “foreach eachfor forall allfor alleach eachall";
Pattern p = Pattern.compile(“(?<!for)each");// 任意先行forが含まないeachをマッチング
Matcher match = p.matcher(testStr);
while (match.find()) {
System.out.println(match.group());
}
System.out.println(“——————————–“);
p = Pattern.compile(“(?<=for)each");// 任意先行forが含まるeachをマッチング
match = p.matcher(testStr);
while (match.find()) {
System.out.println(match.group());
}
System.out.println(“——————————-“);
p = Pattern.compile(“for(?!each)");// 任意後ろforが含まれないeachをマッチング
match = p.matcher(testStr);
while (match.find()) {
System.out.println(match.group());
}
System.out.println(“——————————-“);
p = Pattern.compile(“for(?=each)");//任意後ろforが含まれるeachをマッチング
match = p.matcher(testStr);
while (match.find()) {
System.out.println(match.group());
}
}

実行結果:
each
each
each
——————————–
each
——————————-
for
for
for
——————————-
for

Development

Posted by arkgame