在JavaScript中使用正則表示式匹配特定單詞?


任務是使用正則表示式匹配字串中的特定單詞或字元。

正則表示式 (regex) 是一種用於匹配字串中字元組合的模式。這裡我們包括test()match()matchAll() 方法來匹配正則表示式中的以下單詞。

我們有一些邊界型別斷言,其中我們使用了 \b。

考慮一個句子:“mickey is holding mic.”

使用正則表示式 - \bmic\b 將匹配單詞mic,但不匹配mickey中的mic。這是一個單詞邊界。另一個斷言是(g),它是一個全域性搜尋標誌。

考慮一個句子:“me and me are mine with me”。

const sentence = 'me and me are mine with me'; const regex = /me/; document.write(sentence.match(regex)); //me

在上述情況下,我們沒有在正則表示式中使用 (g),因此它只返回第一個匹配值。

const sentence = 'me and me are mine with me'; const regex = /me/g; document.write(sentence.match(regex)); //me, me, me

這裡,我們在正則表示式中使用了 (g),所以它返回了整個句子中所有“me”單詞。

使用 test() 方法

test() 方法將在正則表示式和輸入字串之間搜尋匹配的單詞。此方法將返回布林值作為輸出。

示例

以下是一個示例,用於將正則表示式中的單詞與輸入字串匹配:

<!DOCTYPE html> <html> <head> <title>Match specific word in regex in JavaScript</title> </head> <body> <script> var line = "Karthikeya is massive hit in hindi belt"; var regex = /\bmassive\b/g; var res = regex.test(line); document.write(res); </script> </body> </html>

正如我們在下面的輸出中看到的,它透過將正則表示式與字串句子進行比較,返回了正則表示式中的值。

使用 match() 方法

match() 方法將返回與字串匹配的結果。這將以不同型別返回輸出:

  • 如果字串中存在任何匹配項,它將返回包含匹配值的陣列。

  • 如果字串中沒有任何匹配項,它將返回 Null。

示例 1

讓我們看看下面的示例,它將匹配值作為輸出返回,如果無匹配則返回 Null。

<!DOCTYPE html> <html> <head> <title>Match specific word in regex in JavaScript</title> </head> <body> <script> const line = 'RRR became famous all over the globe'; const regex1 = /RRR/; const regex2 = /KGF/; document.write(line.match(regex1),"<br>"); //RRR document.write(line.match(regex2)); //Null </script> </body> </html>

正如我們在下面的輸出中看到的,它將匹配值作為陣列返回,如果正則表示式的值在字串中任何地方都不匹配,則返回 Null:

示例 2

使用全域性標誌 (g)

正如我們上面所討論的,如果我們將 (g) 提供給正則表示式的值,它將迭代整個字串句子,並在字串句子中出現匹配的單詞的任何地方返回它。

<!DOCTYPE html> <html> <head> <title>Match specific word in regex in JavaScript</title> </head> <body> <script> const line = 'Rajamouli is the reason for RRR becaming famous all over the globe'; const regex1 = /the/g; document.write(line.match(regex1),"<br>"); //RRR </script> </body> </html>

在下面的輸出中,透過使用全域性標誌 (g),它返回了輸入字串句子中出現的任何地方的匹配值。

示例 3

使用不區分大小寫的搜尋標誌 (i)

另一個斷言是 (i),它是不區分大小寫的搜尋標誌。

如果我們在正則表示式中使用此 (i) 不區分大小寫的搜尋標誌,它將返回所有匹配值,無論它們是大寫還是小寫。

以下是一個示例,我們不考慮大小寫的情況下將正則表示式與字串匹配。

<!DOCTYPE html> <html> <head> <title>Match specific word in regex in JavaScript</title> </head> <body> <script> const Dhoni = 'We are all servents and we are doing national duty.'; const regex1 = /we/gi; document.write(Dhoni.match(regex1)); </script> </body> </html>

正如我們在下面給出的輸出中看到的,它返回了所有與正則表示式匹配的值,而不考慮大小寫。

使用 matchAll() 方法

全域性搜尋標誌 (g) 對.matchAll() 是必需的,它要麼返回迭代器,要麼返回空陣列。

我們需要使用展開運算子 (…) 來將字串中的元素作為一系列值獲取。

示例

以下是如何使用matchAll() 方法將正則表示式中的單詞與指定的字串句子匹配的示例:

<!DOCTYPE html> <html> <head> <title>Match specific word in regex in JavaScript</title> </head> <body> <script> const Dhoni = 'We are all servents and we are doing national duty.'; const regex1 = /we/gi; document.write(...Dhoni.matchAll(regex1)); </script> </body> </html>

在輸出中,matchAll() 方法返回整個字串句子中所有與正則表示式匹配的值。

更新於:2022年9月22日

瀏覽量 10K+

啟動您的職業生涯

完成課程後獲得認證

開始學習
廣告