JavaScriptで正規表現を使用する5つの方法

JavaScriptで正規表現を書く一般的な使用法をいくつか紹介します。

1. match()

match()は文字列とともに使用され、正規表現を引数として、文字列と正規表現regexの間の一致をチェックします。

構文

str.match(regex);

このメソッドは、次の3つの可能な値を返します。

  • 正規表現にグローバル一致であるgタグが含まれている場合、グループ情報をキャプチャせずに、すべての一致を含む配列を返します。
  • 正規表現にgタグがない場合は、最初の一致とそれに関連するキャプチャグループを含む配列を返します。
  • 一致するものがまったくない場合はnullを返します。
groups:キーがnameで値がcaptureinggroupであるcaptureinggroupsという名前のオブジェクト、または名前付きキャプチャーグループが定義されていない場合はundefined。

タグgのサンプルコード

const strText = "Hello China";
const regex = /[A-Z]/g; // 大写字母正则表达式
console.log(strText.match(regex)); // [ 'H', 'C' ]

タグgのないサンプルコード

const text = 'Hello World';
const regex = /[A-Z]/; //Capital letters regex.
console.log(text.match(regex)); // [ 'H', index: 0, input: 'Hello China', groups: undefined ]

一致するインスタンスコードがない場合:

const strText = "hello china";
const regex = /[A-Z]/; // 大写字母正则表达式
console.log(strText.match(regex)); // null

2. test()

test()は、指定された文字列と正規表現の一致をテストし、引数として文字列を受け入れ、一致するかどうかに応じてtrueまたはfalseを返します。

以下の文字列strTextにchinaという単語が含まれているかどうかを確認するとします。単語を検索するための正規表現を作成し、正規表現と文字列strTextの一致をテストできます。

const strText = "hello china";
const regex = /china/;
console.log(regex.test(strText)); // true

一致しないサンプルコードは次のとおりです。

const strText = "hello China";
const regex = /china/;
console.log(regex.test(strText)); // false

上記のコードからわかるように、caseはマッチング結果に影響します。caseを無視する必要がある場合は、次のようにフラグiを使用する必要があります。

const strText = "hello China";
const regex = /china/i;
console.log(regex.test(strText)); // true
.match()は構文的に.test()の「反対」で あることに 注意 して

3. search()

search()メソッドは、正規表現で使用できる文字列メソッドです。正規表現を引数として渡して、文字列内の一致を検索できます。

このメソッドは、文字列全体の最初の一致の位置(インデックス)を返します。一致がない場合は-1を返します。

一致するインスタンス:

const strText = "hello china,i love china";
const regex = /china/;
console.log(strText.search(regex)); // 6

一致するインスタンスがありません:

const strText = "hello china,i love china";
const regex = /devpoint/;
console.log(strText.search(regex)); // -1

4. replace()

replace()は、指定された値または正規表現の文字列を検索し、それを別の値に置き換えます。メソッドは2つのパラメーターを受け入れます。

  1. 検索する値
  2. 置き換える新しい値

このメソッドは、置き換えられた値を含む新しい文字列を返します。元の文字列は変更されず、検索された最初の値のみが置き換えられることに注意してください

コード例:

const strText = "hello world,i love world";
const regex = /world/;
console.log(strText.replace(regex, "china")); // hello china,i love world

5. replaceAll()

replaceAll()はメソッドreplace()に似ていますが、文字列内の一致するすべての値または正規表現を置き換えることができます。

2つのパラメータを受け入れます。

  1. 検索する値は、通常の場合、グローバルフラグgでマークする必要があります
  2. 置き換える新しい値

元の文字列を変更せずに、すべての新しい値を含む新しい文字列を返します。

コード例:

const strText = "hello world,i love world";
const regex = /world/g;
console.log(strText.replaceAll(regex, "china")); // hello china,i love china

次のコードに相当します。

const strText = "hello world,i love world";
console.log(strText.replaceAll("world", "china")); // hello china,i love china
通常の検索と置換により、グローバルタグgを正規表現に追加すると、次のように、通常の条件を満たすすべての文字列を置き換えることもできます。
const strText = "hello world,i love world";
const regex = /world/g;
console.log(strText.replace(regex, "china")); // hello china,i love china

おすすめ

転載: blog.csdn.net/z591102/article/details/120011104