「JavaScript」正規表現メソッドexecの使い方

関数
exec() メソッドは、指定された文字列内で一致するものの検索を実行します。
結果の配列、または null を返します。
正規表現のマッチが成功した場合、execメソッドは配列を返します。
配列のインデックス 0 には最後にマッチした文字が、インデックス 1 以降には括弧で囲まれた部分文字列のマッチがセットされます。
マッチに失敗した場合execメソッドは null を返します。

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
var resA = /ark/.exec("starkfg");
console.log(resA);
console.log(resA[0]);
console.log("*********結果2************")
var resB = /(.+)ark(f)/.exec("stbarkfg");
console.log(resB);
console.log(resB[1]);
console.log(resB[2]);
console.log("--------結果3--------")
var resC = /ark/.exec("studyskill");
console.log(resC); // null
var resA = /ark/.exec("starkfg"); console.log(resA); console.log(resA[0]); console.log("*********結果2************") var resB = /(.+)ark(f)/.exec("stbarkfg"); console.log(resB); console.log(resB[1]); console.log(resB[2]); console.log("--------結果3--------") var resC = /ark/.exec("studyskill"); console.log(resC); // null
var resA = /ark/.exec("starkfg");
console.log(resA);  
console.log(resA[0]); 

console.log("*********結果2************")
var resB = /(.+)ark(f)/.exec("stbarkfg");
console.log(resB); 
console.log(resB[1]);  
console.log(resB[2]); 

console.log("--------結果3--------")
var resC = /ark/.exec("studyskill");
console.log(resC);  // null

実行結果

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
Array ["ark"]
"ark"
"*********結果2************"
Array ["stbarkf", "stb", "f"]
"stb"
"f"
"--------結果3--------"
null
Array ["ark"] "ark" "*********結果2************" Array ["stbarkf", "stb", "f"] "stb" "f" "--------結果3--------" null
Array ["ark"]
"ark"
"*********結果2************"
Array ["stbarkf", "stb", "f"]
"stb"
"f"
"--------結果3--------"
null

 

JavaScript

Posted by arkgame