跳轉至內容

JavaScript/正則表示式

來自Wikibooks,開放世界中的開放書籍
上一頁:陣列 索引 下一頁:運算子

JavaScript 在字串中搜索匹配項時實現了正則表示式(簡稱 regex)。與其他指令碼語言一樣,這允許超越簡單的逐字匹配進行搜尋,甚至可以用於解析特定格式的字串。

與字串不同,正則表示式以斜槓(/)字元分隔,並且可能附加一些選項。

正則表示式最常與 string.match() 和 string.replace() 方法結合使用。

概覽,舉例說明

strArray = "Hello world!".match(/world/); // Singleton array; note the slashes
strArray = "Hello!".match(/l/g); // Matched strings are returned in a string array
"abc".match(/a(b)c/)[1] === "b" // Matched subgroup is the 2nd item (index 1)
str1 = "Hey there".replace(/Hey/g, "Hello");
str2 = "N/A".replace(/\//g, ","); // Slash is escaped with \
str3 = "Hello".replace(/l/g, "m").replace(/H/g, "L").replace(/o/g, "a"); // Pile
if (str3.match(/emma/)) { console.log("Yes"); }
if (str3.match("emma")) { console.log("Yes"); } // Quotes work as well
"abbc".replace(/(.)\1/g, "$1") === "abc" // Backreference

相容性

[編輯 | 編輯原始碼]

JavaScript 的正則表示式集遵循擴充套件集。雖然將 Regex 模式從 JavaScript 複製到其他位置可能會按預期工作,但某些較舊的程式可能無法按預期工作。

  • 在搜尋詞中,\1 用於反向引用匹配的組,如其他實現中一樣。
  • 在替換字串中,$1 被替換為搜尋中匹配的組,而不是 \1。
    • 示例:"abbc".replace(/(.)\1/g, "$1") => "abc"
  • | 是魔法字元,\| 是字面量
  • ( 是魔法字元,\( 是字面量
  • 語法 (?=...), (?!...), (?<=...), 和 (?<!...) 不可用。
  • 匹配
    • string = "Hello world!".match(/world/);
    • stringArray = "Hello world!".match(/l/g); // 匹配的字串將返回到字串陣列中
    • "abc".match(/a(b)c/)[1] => "b" // 匹配的子組是結果陣列的第二個成員(索引為“1”)
  • 替換
    • string = string.replace(/不帶引號的表示式/g, "替換");
    • string = string.replace(/以這種方式\/轉義斜槓/g, "替換");
    • string = string.replace( ... ).replace ( ... ). replace( ... );
  • 測試
    • if (string.match(/不帶引號的正則表示式/)) {

修飾符

[編輯 | 編輯原始碼]

單字母修飾符

g 全域性。匹配列表將返回到陣列中。
i 不區分大小寫的搜尋
m 多行。如果運算元字串有多行,則 ^ 和 $ 匹配字串中每一行的開頭和結尾,而不是僅匹配整個字串的開頭和結尾
"a\nb\nc".replace(/^b$/g,"d") === "a\nb\nc"
"a\nb\nc".replace(/^b$/gm,"d") === "a\nd\nc"

   

運算子

[編輯 | 編輯原始碼]
運算子 效果
\b 匹配單詞的邊界。
\w 匹配字母數字字元,包括“_”。
\W \w 的否定。
\s 匹配空格字元(空格、製表符、換行符、換頁符)
\S \s 的否定。
\d 匹配數字。
\D \d 的否定。


函式呼叫

[編輯 | 編輯原始碼]

對於複雜操作,函式可以處理匹配的子字串。在以下程式碼中,我們將所有單詞大寫。由於要大寫的每個字母都是不同的字元,因此無法透過簡單的替換來完成

var capitalize = function(matchobj) {
  var group1 = matchobj.replace(/^(\W)[a-zA-Z]+$/g, "$1");
  var group2 = matchobj.replace(/^\W([a-zA-Z])[a-zA-Z]+$/g, "$1");
  var group3 = matchobj.replace(/^\W[a-zA-Z]([a-zA-Z]+)$/g, "$1");
  return group1 + group2.toUpperCase() + group3;
};

var classicText = "To be or not to be?";

var changedClassicText = classicText.replace(/\W[a-zA-Z]+/g, capitalize);

console.log(changedClassicText==="To Be Or Not To Be?");

該函式針對每個子字串呼叫。以下是函式的簽名

function (''<matchedSubstring>[, <capture1>, ...<captureN>, <indexInText>, <entireText>]'') {
 ...
 return ''<stringThatWillReplaceInText>'';
}
  • 第一個引數是與模式匹配的子字串。
  • 接下來的引數是子字串中的捕獲。引數的數量與捕獲的數量相同。
  • 下一個引數是從文字開頭開始的子字串開頭的索引。
  • 最後一個引數是整個文字的其餘部分。
  • 返回值將放在文字中,而不是匹配的子字串。
[編輯 | 編輯原始碼]


上一頁:陣列 索引 下一頁:運算子
華夏公益教科書