トップページに戻る
次の正規表現パズルへ
前の正規表現パズルへ
10-1 Javaの正規表現の使用例
正規表現パズル
//HelloWorld (Java環境を覚える)
public class sample1{
public static void main(String argv[]){
System.out.println("HelloJava");
}
}
//1から100までの和を求める (forを覚える)
public class sample2{
public static void main(String argv[]){
int sum = 0;
for (int i=0;i<=100;i++) sum+=i;
System.out.println("sum from 1 to 100 = " + Integer.toString(sum));
}
}
//1から100までの和を求める (whileを覚える)
public class sample3{
public static void main(String argv[]){
int sum = 0,i = 0;
while (i <= 100) sum+=i++;
System.out.println("sum from 1 to 100 = " + Integer.toString(sum));
}
}
//FizzBuzz問題 (ifを覚える)
public class sample4{
public static void main(String argv[]){
for (int i=1;i<=100;i++){
if (i%3 == 0 && i%5==0) System.out.println("FizzBuzz");
else if (i%3 == 0) System.out.println("Fizz");
else if (i%5 == 0) System.out.println("Buzz");
else System.out.println(Integer.toString(i));
}
}
}
//1から100までを配列にセット (配列の扱いを覚える)
public class sample5{
public static void main(String argv[]){
int[] intArray = new int[100+1];
for (int i=1;i<=100;i++) intArray[i] = i;
for (int i=1;i<=100;i++) System.out.println(Integer.toString(intArray[i]));
}
}
//正規表現で^[ac][1-8]な文字列を検索 (正規表現の扱い方を覚える)
import java.util.regex.*;
public class sample6{
private static final String PATTERN = "^[ac][1-8]";
public static void main(String argv[]){
String[] strArray = new String[9+1];
strArray[1] = "a15";
strArray[2] = "a81";
strArray[3] = "a92";
strArray[4] = "b13";
strArray[5] = "b84";
strArray[6] = "b96";
strArray[7] = "c17";
strArray[8] = "c88";
strArray[9] = "c99";
System.out.println("Pattern " + PATTERN);
Pattern p = Pattern.compile(PATTERN);
for (int i=1;i<=9;i++){
String willOut = "Line" + Integer.toString(i) + " " + strArray[i] + " ";
Matcher m = p.matcher(strArray[i]);
if (m.find()) willOut += "matchs " + m.group();
else willOut += "no match";
System.out.println(willOut);
}
}
}
//実行結果
Pattern ^[ac][1-8]
Line1 a15 matchs a1
Line2 a81 matchs a8
Line3 a92 no match
Line4 b13 no match
Line5 b84 no match
Line6 b96 no match
Line7 c17 matchs c1
Line8 c88 matchs c8
Line9 c99 no match