トップページに戻る    次のJavaScriptのサンプルへ    前のJavaScriptのサンプルへ

1-6 正規表現で文字列を検索 (正規表現の扱い方を覚える)

JavaScriptのサンプル

正規表現で^[ac][1-8]な文字列を検索します。


ソース

strArray = new Array();
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";

PATTERN = "^[ac][1-8]";
reg = new RegExp(PATTERN);
document.write("Pattern " ,PATTERN , "<br>");

for(I=1 ; I<strArray.length ; I++){
    WillOut = "Line" + String(I) + " " + strArray[I] + " ";
    mat = strArray[I].match(reg);

    if (mat != null)
        WillOut += "matchs " + mat[0];
    else WillOut += "no match";
    document.write(WillOut, "<br>");
}


実行結果

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


解説

RegExpオブジェクトを使用してます。