tech.chakapoko.com
Home / Node.js / 文字列

[Node.js][JavaScript]正規表現を使う

正規表現にマッチしているかを調べる(String#match メソッド)

正規表現のパターンにマッチするかどうかを調べる時には String#match メソッドを使います。

match メソッドは配列を返します。キャプチャした部分文字列は result[1] のようにして取り出せます。

const s = 'https://example.com/index.html';

const result = s.match(/https?:\/\/(.*?)\/index.html/);

console.log(result[0]); // => https://example.com/index.html
console.log(result[1]); // => example.com

パターンにマッチしなかった時は null を返します。

const s = 'https://example.com/index.html';
const result = s.match(/not match/);
console.log(result); // => null

正規表現にマッチしているかを調べる(RegExp#exec メソッド)

String#match の代わりに RegExp#exec を使うこともできます。

const s = 'https://example.com/index.html';

const result = /https?:\/\/(.*?)\/index.html/.exec(s);

console.log(result);

console.log(result[0]); // => https://example.com/index.html
console.log(result[1]); // => example.com

パターンにマッチしなかった時は String#match 同様に null を返します。

const s = 'https://example.com/index.html';
const result = /not match/.exec(s);
console.log(result); // => null

正規表現にマッチしているかを調べる(RegExp#test メソッド)

正規表現のパターンにマッチしているかどうかだけを知りたい時は真偽値を返す RegExp#test が使えます。

const s = 'https://example.com/index.html';

console.log(/https?:\/\/(.*?)\/index.html/.test(s)); // => true
console.log(/not match/.test(s));                    // => false

正規表現を使って文字列を置換する

正規表現を使って文字列を置換するには String#replace を使います。

const s = 'http://example.com';

console.log(s.replace(/http/, "https")); // => https://example.com
console.log(s.replace(/(http)/, "$1s")); // => https://example.com

第1引数に正規表現のパターンを、第2引数に置換する文字列を指定します。第2引数ではキャプチャした文字列を $1, $2... という形式で利用できます。

正規表現を使って文字列を分割する

正規表現を使って文字列を分割するには String#split を使います。

const lines = "a\nb\nc";
console.log(lines.split(/\n/)); // => [ 'a', 'b', 'c' ]