JavaScriptのRegExpオブジェクトによるパターンマッチングの極意

JavaScriptのRegExpオブジェクトによるパターンマッチングの極意

RegExpオブジェクトを使えば、文字列操作がより柔軟になります。本記事では、正規表現を使ったパターンマッチングの基本から応用までを網羅します。

RegExpオブジェクトの作成方法

正規表現はリテラルまたはコンストラクタで作成できます。

// リテラル
const regex1 = /abc/;
// コンストラクタ
const regex2 = new RegExp('abc');

基本的なパターンマッチング

testメソッドで文字列にパターンが含まれるかを確認します。

const regex = /hello/;
console.log(regex.test('hello world')); // true
console.log(regex.test('goodbye')); // false

文字クラスを使用した柔軟な検索

[ ]で特定の文字セットを指定します。

const regex = /[aeiou]/;
console.log(regex.test('cat')); // true
console.log(regex.test('sky')); // false

特殊文字のエスケープ

特殊文字はバックスラッシュでエスケープします。

const regex = /\./;
console.log(regex.test('file.txt')); // true
console.log(regex.test('filetxt')); // false

繰り返しを表すメタ文字

*, +, ?で繰り返し回数を指定します。

const regex = /a+/;
console.log(regex.test('aaa')); // true
console.log(regex.test('b')); // false

位置指定子で特定の位置をマッチ

^$を使って文字列の位置を指定します。

const regex = /^hello/;
console.log(regex.test('hello world')); // true
console.log(regex.test('world hello')); // false

正規表現フラグの活用

フラグで検索条件を拡張します。

// g: 全体検索, i: 大文字小文字無視
const regex = /hello/gi;
console.log('Hello hello'.match(regex)); // [ 'Hello', 'hello' ]

マッチング結果の取得

matchメソッドで詳細な結果を取得します。

const regex = /(\d+)-(\d+)-(\d+)/;
const result = '2023-12-19'.match(regex);
console.log(result);
// [
//   '2023-12-19',
//   '2023',
//   '12',
//   '19'
// ]

置換と正規表現

replaceメソッドを使った文字列置換。

const regex = /\d+/g;
const result = 'The year is 2023'.replace(regex, '****');
console.log(result); // The year is ****

グループ化で複雑なパターンを扱う

括弧で部分をグループ化できます。

const regex = /(cat|dog)/;
console.log(regex.test('I love cats')); // true
console.log(regex.test('I love dogs')); // true
console.log(regex.test('I love birds')); // false

LookaheadとLookbehind

条件付きマッチングを行います。

// ポジティブLookahead
const regex = /foo(?=bar)/;
console.log(regex.test('foobar')); // true
console.log(regex.test('fooqux')); // false

// ネガティブLookbehind
const regex2 = /(?<!not )allowed/;
console.log(regex2.test('allowed')); // true
console.log(regex2.test('not allowed')); // false

RegExpオブジェクトの動的生成

動的に正規表現を作成します。

const word = 'hello';
const regex = new RegExp(`\\b${word}\\b`);
console.log(regex.test('hello world')); // true
console.log(regex.test('world hello')); // true

正規表現をデバッグするコツ

正規表現の可読性を保つには、コメントを活用したり、パターンを分割します。

const regex = new RegExp(
  [
    '^\\d{4}',  // 年
    '-\\d{2}',  // 月
    '-\\d{2}$'  // 日
  ].join('')
);
console.log(regex.test('2023-12-19')); // true

まとめ

JavaScriptのRegExpオブジェクトを使いこなすことで、文字列処理が効率化され、柔軟性が向上します。基本的なパターンから応用的な機能まで学ぶことで、複雑な処理もシンプルに実現できます。