<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                ??一站式輕松地調用各大LLM模型接口,支持GPT4、智譜、豆包、星火、月之暗面及文生圖、文生視頻 廣告
                # JavaScript 正則表達式 > 原文: [http://zetcode.com/javascript/regularexpressions/](http://zetcode.com/javascript/regularexpressions/) JavaScript 正則表達式教程展示了如何在 JavaScript 中使用正則表達式。 正則表達式用于文本搜索和更高級的文本操作。 正則表達式是內置工具,如`grep`,`sed`,文本編輯器(如 vi,emacs),編程語言(如 JavaScript,Perl 和 Python)。 ## JavaScript 正則表達式 在 JavaScript 中,我們使用斜線`//`或`RegExp`對象構建正則表達式。 模式是一個正則表達式,用于定義我們正在搜索或操縱的文本。 它由文本文字和元字符組成。 元字符是控制正則表達式計算方式的特殊字符。 例如,使用`\s`,我們搜索空白。 創建模式后,可以使用其中一個函數將模式應用于文本字符串。 函數包括`test()`,`match()`,`search()`和`replace()`。 下表顯示了一些正則表達式: | 正則表達式 | 含義 | | --- | --- | | `.` | 匹配任何單個字符。 | | `?` | 一次匹配或根本不匹配前面的元素。 | | `+` | 與前面的元素匹配一次或多次。 | | `*` | 與前面的元素匹配零次或多次。 | | `^` | 匹配字符串中的起始位置。 | | `$` | 匹配字符串中的結束位置。 | | <code>&#124;</code> | 備用運算符。 | | `[abc]` | 匹配`a`或`b`或`c`。 | | `[a-c]` | 范圍; 匹配`a`或`b`或`c`。 | | `[^abc]` | 否定,匹配除`a`或`b`或`c`之外的所有內容。 | | `\s` | 匹配空白字符。 | | `\w` | 匹配單詞字符; 等同于`[a-zA-Z_0-9]` | ## 測試函數 `test()`方法執行搜索以查找正則表達式和指定字符串之間的匹配項。 它返回`true`或`false`。 `test_fun.js` ```js let words = ['book', 'bookworm', 'Bible', 'bookish','cookbook', 'bookstore', 'pocketbook']; let pattern = /book/; words.forEach(word => { if (pattern.test(word)) { console.log(`the ${word} matches`); } }); ``` 在示例中,我們有一個單詞數組。 模式將在每個單詞中尋找一個`"book"`字符串。 ```js let pattern = /book/; ``` 我們使用斜線創建一個模式。 正則表達式由四個普通字符組成。 ```js words.forEach(word => { if (pattern.test(word)) { console.log(`the ${word} matches`); } }); ``` 我們遍歷數組并調用`test()`函數。 如果模式與單詞匹配,則返回`true`。 ```js $ node test_fun.js the book matches the bookworm matches the bookish matches the cookbook matches the bookstore matches the pocketbook matches ``` 這些單詞與模式匹配。 ## `search()`函數 `search()`函數返回正則表達式與給定字符串之間的第一個匹配項的索引。 如果找不到匹配項,則返回 -1。 `search_fun.js` ```js let text = 'I saw a fox in the wood. The fox had red fur.'; let pattern = /fox/; let idx = text.search(pattern); console.log(`the term was found at index: ${idx}`); ``` 在該示例中,我們找出`"fox"`項的第一個匹配項的索引。 ```js $ node search_fun.js the term was found at index: 8 ``` 這是輸出。 ## `exec`函數 `exec()`執行搜索以查找指定字符串中的匹配項。 它返回一個帶有匹配信息的對象。 `exec_fun.js` ```js let words = ['book', 'bookworm', 'Bible', 'bookish', 'cookbook', 'bookstore', 'pocketbook']; let pattern = /book/; words.forEach(word => { let res = pattern.exec(word); if (res) { console.log(`${res} matches ${res.input} at index: ${res.index}`); } }); ``` 在示例中,我們使用`exec()`將模式應用于輸入字符串。 ```js if (res) { console.log(`${res} matches ${res.input} at index: ${res.index}`); } ``` 我們打印有關比賽的信息。 它包括比賽開始的索引。 ```js $ node exec_fun.js book matches book at index: 0 book matches bookworm at index: 0 book matches bookish at index: 0 book matches cookbook at index: 4 book matches bookstore at index: 0 book matches pocketbook at index: 6 ``` 這是輸出。 ## `match()`函數 當將模式與輸入字符串進行匹配時,`match()`函數將檢索匹配項。 `match_fun.js` ```js let text = 'I saw a fox in the wood. The fox had red fur.'; let pattern = /fox/g; let found = text.match(pattern); console.log(`There are ${found.length} matches`); ``` 在該示例中,我們找出`"fox"`項的出現次數。 ```js let pattern = /fox/g; ``` `g`字符是一個標志,可查找所有出現的術語。 通常,當找到第一個匹配項時,搜索結束。 ```js $ node match_fun.js There are 2 matches ``` 我們在字符串中找到了兩個`"fox"`術語。 ## `replace()`函數 `replace()`函數返回一個新字符串,該字符串的部分或全部匹配都由替換字符串替換。 `replace_fun.js` ```js let text = 'He has gray hair; gray clouds gathered above us.' let pattern = /gray/g; let new_text = text.replace(pattern, 'grey'); console.log(new_text); ``` 在示例中,我們從輸入字符串中創建了一個新字符串,在此我們將`"gray"`單詞替換為`'grey'`。 ```js let pattern = /gray/g; ``` `g`字符是一個標志,可查找所有出現的術語。 ```js $ node replacing.js He has grey hair; grey clouds gathered above us. ``` 這是輸出。 ## 不區分大小寫的匹配 要啟用不區分大小寫的搜索,我們使用`i`標志。 `case_insensitive.js` ```js let words = ['dog', 'Dog', 'DOG', 'Doggy']; let pattern = /dog/i; words.forEach(word => { if (pattern.test(word)) { console.log(`the ${word} matches`); } }); ``` 在示例中,無論大小寫如何,我們都將模式應用于單詞。 ```js let pattern = /dog/i; ``` 附加`i`標志,我們進行不區分大小寫的搜索。 ```js $ node case_insensitive.js the dog matches the Dog matches the DOG matches the Doggy matches ``` 執行不區分大小寫的搜索時,所有四個單詞都與模式匹配。 ## 點元字符 點(。)元字符代表文本中的任何單個字符。 `dot_meta.js` ```js let words = ['seven', 'even', 'prevent', 'revenge', 'maven', 'eleven', 'amen', 'event']; let pattern = /..even/; words.forEach(word => { if (pattern.test(word)) { console.log(`the ${word} matches`); } }); ``` 在示例中,我們在一個數組中有八個單詞。 我們在每個單詞上應用一個包含兩個點元字符的模式。 ```js $ node dot_meta.js the prevent matches the eleven matches ``` 有兩個與模式匹配的單詞。 ## 問號元字符 問號(?)元字符是與上一個元素零或一次匹配的量詞。 `question_mark_meta.js` ```js let words = ['seven', 'even', 'prevent', 'revenge', 'maven', 'eleven', 'amen', 'event']; let pattern = /.?even/; words.forEach(word => { if (pattern.test(word)) { console.log(`the ${word} matches`); } }); ``` 在示例中,我們在點字符后添加問號。 這意味著在模式中我們可以有一個任意字符,也可以在那里沒有任何字符。 ```js $ node question_mark_meta.js the seven matches the even matches the prevent matches the revenge matches the eleven matches the event matches ``` 這次,沒有前一個字符的偶數和事件字也匹配。 ## 錨點 錨點匹配給定文本內字符的位置。 當使用^錨時,匹配必須發生在字符串的開頭,而當使用$錨時,匹配必須發生在字符串的結尾。 `anchors.js` ```js let sentences = ['I am looking for Jane.', 'Jane was walking along the river.', 'Kate and Jane are close friends.']; let pattern = /^Jane/; sentences.forEach(sentence => { if (pattern.test(sentence)) { console.log(`${sentence}`); } }); ``` 在示例中,我們有三個句子。 搜索模式為`^Jane`。 該模式檢查`"Jane"`字符串是否位于文本的開頭。 `Jane\.`將在句子結尾處查找`"Jane"`。 ## 精確匹配 可以通過在錨點^和$之間放置術語來進行精確匹配。 `exact_match.js` ```js let words = ['seven', 'even', 'prevent', 'revenge', 'maven', 'eleven', 'amen', 'event'] let pattern = /^even$/; words.forEach(word => { if (pattern.test(word)) { console.log(`the ${word} matches`); } }); ``` 在示例中,我們尋找`'even'`項的精確匹配。 ```js $ node exact_match.js the even matches ``` 這是輸出。 ## 字符類 字符類定義了一組字符,任何字符都可以出現在輸入字符串中以使匹配成功。 `character_class.js` ```js let words = ['a gray bird', 'grey hair', 'great look']; let pattern = /gr[ea]y/; words.forEach(word => { if (pattern.test(word)) { console.log(`${word}`); } }); ``` 在該示例中,我們使用字符類同時包含灰色和灰色單詞。 ```js let pattern = /gr[ea]y/; ``` `[ea]`類允許在模式中使用'e'或'a'字符。 ## 命名字符類 有一些預定義的字符類。 `\s`與空白字符`[\t\n\t\f\v]`匹配,`\d`與數字`[0-9]`匹配,`\w`與單詞字符`[a-zA-Z0-9_]`匹配。 `named_character_class.js` ```js let text = 'We met in 2013\. She must be now about 27 years old.'; let pattern = /\d+/g; while ((found = pattern.exec(text)) !== null) { console.log(`found ${found} at index ${found.index}`); } ``` 在示例中,我們在文本中搜索數字。 ```js let pattern = /\d+/g; ``` `\d+`模式在文本中查找任意數量的數字集。 `g`標志使搜索在第一次出現時不會停止。 ```js while ((found = pattern.exec(text)) !== null) { console.log(`found ${found} at index ${found.index}`); } ``` 要查找所有匹配項,我們在`while`循環中使用`exec()`函數。 ```js $ node named_character_class.js found 2013 at index 10 found 27 at index 38 ``` 這是輸出。 在下面的示例中,我們有使用`match()`函數的替代解決方案。 `count_numbers.js` ```js let text = 'I met her in 2012\. She must be now about 27 years old.' let pattern = /\d+/g; var found = text.match(pattern); console.log(`There are ${found.length} numbers`); found.forEach((num, i) => { console.log(`match ${++i}: ${num}`); }); ``` 要計算數字,我們使用`\d`命名類。 ```js $ node count_numbers.js There are 2 numbers match 1: 2012 match 2: 27 ``` 這是輸出。 ## 數詞 在下一個示例中,我們計算文本中的單詞數。 `count_words.js` ```js let text = 'The Sun was shining; I went for a walk.'; let pattern = /\w+/g; let found = text.match(pattern); console.log(`There are ${found.length} words`); ``` `\w`名稱集代表一個字字符。 ```js let pattern = /\w+/g; ``` 該模式使用量詞(+)搜索一個或多個單詞字符。 全局標志使搜索查找字符串中的所有單詞。 ```js console.log(`There are ${found.length} words`); ``` 我們將單詞數打印到控制臺。 ```js $ node count_words.js There are 9 words ``` 這是輸出。 ## 交替 交替運算符| 創建具有多種選擇的正則表達式。 `alternations.js` ```js let words = ["Jane", "Thomas", "Robert", "Lucy", "Beky", "John", "Peter", "Andy"]; let pattern = /Jane|Beky|Robert/; words.forEach(word => { if (pattern.test(word)) { console.log(`the ${word} matches`); } }); ``` 列表中有八個名稱。 ```js let pattern = /Jane|Beky|Robert/; ``` 此正則表達式查找`Jane`,`"Beky"`或`"Robert"`字符串。 ## 捕獲組 捕獲組是一種將多個字符視為一個單元的方法。 通過將字符放置在一組圓括號內來創建它們。 例如,`(book)`是包含`'b', 'o', 'o', 'k'`字符的單個組。 捕獲組技術使我們能夠找出字符串中與正則表達式模式匹配的那些部分。 `capturing_groups.js` ```js content = `<p>The <code>Pattern</code> is a compiled representation of a regular expression.</p>`; let pattern = /(<\/?[a-z]*>)/g; let found = content.match(pattern); found.forEach(tag => { console.log(tag); }); ``` 該代碼示例通過捕獲一組字符來打印提供的字符串中的所有 HTML 標簽。 ```js let found = content.match(pattern); ``` 為了找到所有標簽,我們使用`match()`方法。 ```js $ ./capturing_groups.js <p> <code> </code> </p> ``` 我們找到了四個 HTML 標簽。 ## JavaScript 正則表達式電子郵件示例 在以下示例中,我們創建一個用于檢查電子郵件地址的正則表達式模式。 `emails.js` ```js let emails = ["luke@gmail.com", "andy@yahoocom", "34234sdfa#2345", "f344@gmail.com"]; let pattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9-]+\.[a-zA-Z.]{2,18}$/; emails.forEach(email => { if (pattern.test(email)) { console.log(`${email} matches`); } else { console.log(`${email} does not match`); } }) ``` 本示例提供了一種可能的解決方案。 ```js let pattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9-]+\.[a-zA-Z.]{2,18}$/; ``` 前`^`和后`$`個字符提供精確的模式匹配。 模式前后不允許有字符。 電子郵件分為五個部分。 第一部分是本地部分。 這通常是公司,個人或昵稱的名稱。 `[a-zA-Z0-9._-]+`列出了我們可以在本地部分使用的所有可能字符。 它們可以使用一次或多次。 第二部分由文字`@`字符組成。 第三部分是領域部分。 通常是電子郵件提供商的域名,例如 yahoo 或 gmail。 `[a-zA-Z0-9-]+`是一個字符類,提供可在域名中使用的所有字符。 `+`量詞允許使用這些字符中的一個或多個。 第四部分是點字符。 它前面帶有轉義字符(`\`),以獲取文字點。 最后一部分是頂級域名:`[a-zA-Z.]{2,18}`。 頂級域可以包含 2 到 18 個字符,例如`sk, net, info, travel, cleaning, travelinsurance`。 最大長度可以為 63 個字符,但是今天大多數域都少于 18 個字符。 還有一個點字符。 這是因為某些頂級域包含兩個部分: 例如`co.uk`。 ```js $ node emails.js luke@gmail.com matches andy@yahoocom does not match 34234sdfa#2345 does not match f344@gmail.com matches ``` 這是輸出。 在本章中,我們介紹了 JavaScript 中的正則表達式。 您可能也對以下相關教程感興趣: [JavaScript 數組教程](/javascript/arrays/)和 [Big.js 教程](/javascript/bigjs/)。
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看