如何在 JavaScript 正則表示式中查詢括號之間的字元?


在本教程中,我們將學習如何使用示例在 JavaScript 正則表示式中查詢括號之間的字元。

語法

以下是查詢 JavaScript 正則表示式括號之間字元的語法:

[……]

在上述語法中,您可以將要搜尋的字元或字元組合替換為**點**,而**方括號**是指示使用 JavaScript 正則表示式的基本語法。

以下是您可以用來檢查括號中是否存在不同字元的不同語法的列表:

  • **[x]** - 此語法將檢查句子中是否存在字元**x**。
  • **[xyz]** - 此語法將為您提供句子中是否存在任何字元**x,y,z**或它們的組合的結果。
  • **[A-Z]** - 此語法用於檢查是否存在從大寫**A**到大寫**Z**範圍內的任何字元。
  • **[a-z]** - 此語法用於檢查是否存在從小寫**a**到小寫**z**範圍內的任何字元。
  • **[A-z]** - 此語法用於檢查是否存在從大寫**A**到小寫**z**範圍內的任何字元。

讓我們逐一用程式碼示例討論它們。

演算法

  • **步驟 1** - 我們定義一個句子,在其中檢查 JavaScript 正則表示式括號之間的字元。
  • **步驟 2** - 接下來,我們將根據上面討論的語法,為要檢查的特定字元、字元組合或字元範圍定義正則表示式。
  • **步驟 3** - 在下一步中,我們將使用 JavaScript 的內建**match()** 函式或方法將原始句子與您定義的正則表示式匹配。
  • **步驟 4** - 在最後一步中,我們將顯示將原始句子與正則表示式匹配後獲得的句子。

示例 1

下面的示例將說明如何使用上述語法搜尋 JavaScript 正則表示式括號中存在的特定字元“t”:

<!DOCTYPE html> <html> <body> <h3>Find a character between the brackets in JavaScript RegExp</h3> <p>It will do a global search for the characters that are "t":</p> <p>Original Sentence: tutorials point simply easy learning.</p> <p id="result"></p> <script> let myStr = "tutorials point simply easy learning"; let reg = /[t]/g; let match = myStr.match(reg); document.getElementById("result").innerHTML = match; </script> </body> </html>

我們上面討論的示例將透過列印**t**及其在原始句子中出現的次數來給出輸出。它將正則表示式與原始句子匹配,並記錄**t**出現的次數,然後列印**t**出現的次數。

示例 2

下面的示例將解釋如何使用語法查詢 JavaScript 正則表示式括號中單獨或組合存在的多個字元 (a、b、c):

<!DOCTYPE html> <html> <body> <h3>Find a character between the brackets in JavaScript RegExp</h3> <p>It will do a global search for the characters that are "a, b, c":</p> <p>Original Sentence: Hey there, we are checking for character between the brackets of JavaScript RegExp</p> <p id="result"></p> <script> let myStr = "Hey there, we are checking for character, not between the brackets of JavaScript RegExp."; let reg = /[abc]/g; let match = myStr.match(reg); document.getElementById("result").innerHTML = match; </script> </body> </html>

上面的示例將輸出字元 a、b 和 c 單獨或組合出現在句子中的次數。它使用 JavaScript match 函式獲取每個字元在句子中出現的次數,然後列印所有次數。

示例 3

下面的示例將說明如何使用上述語法一次查詢 JavaScript 正則表示式括號中特定範圍內的字元:

<!DOCTYPE html> <html> <body> <h3>Find a character between the brackets in JavaScript RegExp</h3> <p>It will do a global search for the characters that are in the range "A-Z":</p> <p>Original Sentence: Hey THere, We are Checking for CHaracter Between the Brackets of JavaScript RegExp</p> <p id="result"></p> <script> let myStr = "Hey THere, We are Checking for CHaracter Between the Brackets of JavaScript RegExp."; let reg = /[A-Z]/g; let match = myStr.match(reg); document.getElementById("result").innerHTML = match; </script> </body> </html>

在上面的示例中,我們使用了語法來查詢所有範圍從**A-Z**的字元的出現次數。它將檢查定義範圍內的字元,並使用 match 方法獲取每個字元出現的次數,然後按照從左到右的順序逐個列印每個字元。

在上述討論中,我們學習瞭如何藉助三個不同的示例來查詢 JavaScript 正則表示式括號之間的字元,這些示例分別屬於查詢字元的不同語法。

更新於:2022年10月31日

2K+ 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.