RegExpオブジェクトのソースパターンを文字列として取得:regExp.sourceプロパティの使い方


  • エスケープシーケンスは、そのままの形で返されます。
  • フラグ (g, i, m など) は含まれません。
  • 両端のスラッシュ (/) は含まれません。

例:

const regex = /foo[A-Z][a-z]*bar/;
console.log(regex.source); // 出力: foo[A-Z][a-z]*bar

この例では、regex.sourcefoo[A-Z][a-z]*bar を返します。 これは、正規表現リテラル /foo[A-Z][a-z]*bar/ と同じですが、両端のスラッシュと g フラグがありません。

regExp.source プロパティは、以下の用途で役立ちます。

  • 正規表現パターンの比較
  • 正規表現パターンの文字列化
  • 正規表現パターンのデバッグ

regExp.source プロパティは、単にプロパティにアクセスすることで使用できます。 以下に、いくつかの例を示します。

例 1: 正規表現パターンのデバッグ

const regex = /foo[A-Z][a-z]*bar/;

try {
  const str = "Hello, World!";
  console.log(regex.test(str)); // false
} catch (error) {
  console.error(error.message); // エラーメッセージ: Invalid regular expression: missing closing bracket
}

console.log(regex.source); // 出力: foo[A-Z][a-z]*bar

この例では、regex.source プロパティを使用して、正規表現パターンの問題をデバッグしています。 正規表現リテラルには、閉括弧 (]) が欠けています。

例 2: 正規表現パターンの文字列化

const regex = /foo[A-Z][a-z]*bar/;
const regexString = regex.source;
console.log(regexString); // 出力: foo[A-Z][a-z]*bar

この例では、regExp.source プロパティを使用して、正規表現パターンを文字列に変換しています。 これは、正規表現パターンをログに記録したり、他のプログラムに渡したりする場合に役立ちます。

例 3: 正規表現パターンの比較

const regex1 = /foo[A-Z][a-z]*bar/;
const regex2 = new RegExp(regex1.source);

console.log(regex1 === regex2); // true

この例では、regExp.source プロパティを使用して、2 つの正規表現パターンを比較しています。 2 つの正規表現パターンのソースが同じであるため、true が出力されます。



regExp.source プロパティ

const regex = /foo[A-Z][a-z]*bar/;
console.log(regex.source); // 出力: foo[A-Z][a-z]*bar

RegExp コンストラクタ

const regexString = "foo[A-Z][a-z]*bar";
const regex = new RegExp(regexString);
console.log(regex.source); // 出力: foo[A-Z][a-z]*bar

regExp.test() メソッド

const regex = /foo[A-Z][a-z]*bar/;
const str1 = "Hello, World!";
const str2 = "FooBar";

console.log(regex.test(str1)); // false
console.log(regex.test(str2)); // true

regExp.exec() メソッド

const regex = /foo[A-Z][a-z]*bar/;
const str = "This is a FooBar string.";

const match = regex.exec(str);
console.log(match[0]); // 出力: FooBar

regExp.match() メソッド

const regex = /foo[A-Z][a-z]*|bar/;
const str = "This is a FooBar string, and it also contains a bar.";

const matches = str.match(regex);
console.log(matches); // 出力: ["FooBar", "bar"]

String.prototype.replace() メソッド

const regex = /foo[A-Z][a-z]*bar/;
const str = "This is a FooBar string.";

const newStr = str.replace(regex, "baz");
console.log(newStr); // 出力: This is a baz string.
const regex = /[, .!?]+/;
const str = "This string has commas, periods, and exclamation points.";

const tokens = str.split(regex);
console.log(tokens); // 出力: ["This", "string", "has", "commas", "periods", "and", "exclamation", "points"]


フラグを含めた正規表現パターンの取得

regExp.source プロパティは、フラグ (g、i、m など) を含めません。 フラグを含めた正規表現パターンを取得するには、以下の方法を使用できます。

  • String.prototype.toString() メソッド
const regex = /foo[A-Z][a-z]*bar/gi;
console.log(regex.toString()); // 出力: /foo[A-Z][a-z]*bar/gi
  • RegExp.prototype.toString() メソッド (ES2018 以降)
const regex = /foo[A-Z][a-z]*bar/gi;
console.log(regex.toSource()); // 出力: /foo[A-Z][a-z]*bar/gi

動的に生成された正規表現パターンのソースを取得

regExp.source プロパティは、正規表現リテラルで指定されたパターンのみを返します。 動的に生成された正規表現パターンのソースを取得するには、以下の方法を使用できます。

  • パターン文字列を直接操作する
const pattern = "[0-9]+";
const regex = new RegExp(pattern);
console.log(pattern); // 出力: [0-9]+
  • String.prototype.valueOf() メソッド
const pattern = "[0-9]+";
const regex = new RegExp(pattern);
console.log(regex.pattern.valueOf()); // 出力: [0-9]+

部分一致の検出

regExp.source は、完全一致のみに対応する正規表現パターンのみを返します。 部分一致を検出するには、以下の方法を使用できます。

  • String.prototype.match() メソッドとキャプチャグループ
const regex = /f.*bar/;
const str = "This is a foobar string.";

const matches = str.match(regex);
console.log(matches[0]); // 出力: foobar
  • String.prototype.search() メソッド
const regex = /f.*bar/;
const str = "This is a foobar string.";

const index = str.search(regex);
if (index !== -1) {
  console.log(`"foobar" が見つかりました: ${index} 番目`);
} else {
  console.log('"foobar" が見つかりませんでした');
}

大文字小文字を区別しない照合

regExp.source は、大文字小文字を区別する正規表現パターンのみを返します。 大文字小文字を区別しない照合を行うには、以下の方法を使用できます。

  • i フラグを使用する
const regex = /foo[A-Z][a-z]*bar/i;
const str1 = "Hello, FooBar!";
const str2 = "foobar";

console.log(regex.test(str1)); // true
console.log(regex.test(str2)); // true
  • String.prototype.toLowerCase() または String.prototype.toUpperCase() メソッドを使用する
const regex = /foobar/;
const str1 = "Hello, FooBar!";
const str2 = "foobar";

const lowerStr1 = str1.toLowerCase();
const lowerStr2 = str2.toLowerCase();

console.log(regex.test(lowerStr1)); // true
console.log(regex.test(lowerStr2)); // true

複数行にまたがる正規表現

regExp.source は、単一行の正規表現パターンのみを返します。 複数行にまたがる正規表現を使用するには、以下の方法を使用できます。

  • m フラグを使用する
const regex = /^foo.*bar$/m;
const str = `This is a foobar string.
It spans multiple lines.`;

console.log(regex.test(str)); // true
  • 改行文字 (\n) を明示的に含める
const regex = /^foo.*bar$\n/;
const str = `This is a foobar string.\nIt spans multiple lines.`;

console.log(regex.test(str