JavaScript/String/prototype/match
String.prototype.match()
メソッドは、文字列に対して正規表現パターンのマッチングを実行し、マッチした結果を配列として返します[1]。
構文
編集str.match(regexp)
regexp
: 正規表現オブジェクトまたは正規表現として変換可能な値。指定されなかった場合は、空の正規表現//
として扱われます。
例
編集基本的な正規表現マッチングのプログラム
編集以下のプログラムは、String.prototype.match()
を使用して基本的な正規表現マッチングを行います。
const str = 'The quick brown fox jumps over the lazy dog.'; // 単語を検索 const word = str.match(/fox/); console.log(word); // ["fox", index: 16, input: "The quick brown fox jumps over the lazy dog.", groups: undefined] // マッチしない場合は null を返す const noMatch = str.match(/unicorn/); console.log(noMatch); // null
このプログラムでは、String.prototype.match()
を使用して文字列内の特定の単語を検索しています。マッチした場合は、マッチした文字列と追加情報を含む配列が返され、マッチしない場合は null
が返されます。
グローバルフラグを使用したプログラム
編集以下のプログラムは、String.prototype.match()
をグローバルフラグ付きで使用します。
const str = 'The quick brown fox jumps over the lazy dog. The dog barks.'; // グローバルフラグ (g) を使用して、すべてのマッチを検索 const allMatches = str.match(/the/gi); console.log(allMatches); // ["The", "the", "The"] // 数字を検索 const numbers = 'There are 42 apples and 15 oranges.'; const allNumbers = numbers.match(/\d+/g); console.log(allNumbers); // ["42", "15"]
このプログラムでは、String.prototype.match()
をグローバルフラグ (`g`) 付きで使用して、文字列内のすべてのマッチを検索しています。大文字小文字を区別しないフラグ (`i`) と組み合わせることで、異なる大文字小文字の「the」をすべて検索しています。また、数字パターン (`\d+`) に対するグローバルマッチングの例も示しています。
キャプチャグループを使用したプログラム
編集以下のプログラムは、String.prototype.match()
でキャプチャグループを使用します。
const str = 'JavaScript was created by Brendan Eich in 1995.'; // キャプチャグループを使用 const result = str.match(/(\w+) was created by (\w+ \w+) in (\d+)/); console.log(result); // [ // "JavaScript was created by Brendan Eich in 1995", // "JavaScript", // "Brendan Eich", // "1995", // index: 0, // input: "JavaScript was created by Brendan Eich in 1995.", // groups: undefined // ] // キャプチャグループの内容を取り出す if (result) { const [fullMatch, language, creator, year] = result; console.log(`${language} was created by ${creator} in ${year}.`); // "JavaScript was created by Brendan Eich in 1995." }
このプログラムでは、String.prototype.match()
でキャプチャグループを使用して、文字列の特定の部分を抽出しています。結果の配列の最初の要素は完全なマッチであり、その後にキャプチャグループの内容が続きます。分割代入を使用して、キャプチャグループの内容を簡単に取り出すことができます。
名前付きキャプチャグループを使用したプログラム
編集以下のプログラムは、String.prototype.match()
で名前付きキャプチャグループを使用します。
const dateStr = '2023-04-15'; // 名前付きキャプチャグループを使用 const dateMatch = dateStr.match(/(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/); console.log(dateMatch); // [ // "2023-04-15", // "2023", // "04", // "15", // index: 0, // input: "2023-04-15", // groups: { year: "2023", month: "04", day: "15" } // ] // groups オブジェクトを使用して名前付きキャプチャグループにアクセス if (dateMatch && dateMatch.groups) { const { year, month, day } = dateMatch.groups; console.log(`Year: ${year}, Month: ${month}, Day: ${day}`); // "Year: 2023, Month: 04, Day: 15" }
このプログラムでは、String.prototype.match()
で名前付きキャプチャグループを使用して、日付文字列から年、月、日を抽出しています。名前付きキャプチャグループは groups
オブジェクトにマップされ、各グループに名前でアクセスできます。
matchAll との比較プログラム
編集以下のプログラムは、String.prototype.match()
と String.prototype.matchAll()
の違いを示します。
const str = 'The fox jumped over the fox.'; // match() - グローバル検索 const matches = str.match(/fox/g); console.log(matches); // ["fox", "fox"](マッチした文字列のみの配列) // matchAll() - 詳細情報を含むイテレータを返す const matchesAll = [...str.matchAll(/fox/g)]; console.log(matchesAll); // [ // ["fox", index: 4, input: "The fox jumped over the fox.", groups: undefined], // ["fox", index: 23, input: "The fox jumped over the fox.", groups: undefined] // ] // キャプチャグループを使用した場合の違い const strWithGroups = 'red fox, brown fox'; // match() - グローバル検索時はキャプチャグループ情報が失われる const matchesWithGroups = strWithGroups.match(/(\w+) fox/g); console.log(matchesWithGroups); // ["red fox", "brown fox"](キャプチャグループ情報なし) // matchAll() - キャプチャグループ情報を保持 const matchesAllWithGroups = [...strWithGroups.matchAll(/(\w+) fox/g)]; console.log(matchesAllWithGroups); // [ // ["red fox", "red", index: 0, input: "red fox, brown fox", groups: undefined], // ["brown fox", "brown", index: 9, input: "red fox, brown fox", groups: undefined] // ]
このプログラムでは、String.prototype.match()
と String.prototype.matchAll()
の違いを示しています。match()
メソッドをグローバルフラグ付きで使用した場合は、マッチした文字列の配列のみが返され、キャプチャグループや位置情報などの詳細情報は含まれません。一方、matchAll()
メソッドは各マッチに関するすべての情報を含むイテレータを返します。
注意点
編集- 正規表現のフラグ: グローバルフラグ (`g`) が設定されている場合とそうでない場合で、
match()
メソッドの動作が異なります。
* グローバルフラグなし: 最初のマッチに関する詳細情報を含む配列を返します。 * グローバルフラグあり: すべてのマッチした文字列の配列を返します(詳細情報なし)。
- マッチしない場合: マッチするものがない場合は
null
を返します。 - 文字列引数: 文字列または
RegExp
でないオブジェクトが渡された場合、それは自動的にnew RegExp(obj)
を使用して正規表現オブジェクトに変換されます。 - matchAll との違い: ES2020 で導入された
String.prototype.matchAll()
メソッドは、グローバル検索時でもキャプチャグループや位置情報などの詳細情報を含むイテレータを返します。 - exec メソッド:
match()
メソッドは内部的にRegExp.prototype.exec()
メソッドを使用しています。グローバルフラグが設定されていない場合、match()
の結果はRegExp.prototype.exec()
の結果と同じです。
脚註
編集- ^ このメソッドは、文字列内のパターンを検索するために使用されます。
外部リンク
編集