re.replace

支援的國家/地區:
re.replace(stringText, replaceRegex, replacementText)

說明

執行規則運算式取代作業。

這個函式需要三個引數:

  • stringText:原始字串。
  • replaceRegex:表示要搜尋模式的規則運算式。
  • replacementText:要插入每個相符項目的文字。

傳回衍生自原始 stringText 的新字串,其中所有符合 replaceRegex 模式的子字串都會替換為 replacementText 中的值。您可以在 replacementText 內使用反斜線逸出數字 (\1\9),好在 replaceRegex 模式中插入與對應放入括號內群組相符的文字。請使用 \0 來參照完整的相符文字。

函式會取代非重疊相符項目,並優先取代找到的第一個相符項目。舉例來說,re.replace("banana", "ana", "111") 會傳回字串「b111na」。

參數資料類型

STRINGSTRINGSTRING

傳回類型

STRING

程式碼範例

範例 1

這個範例會擷取電子郵件中 @ 符號後的所有內容,將 com 取代為 org,然後傳回結果。請注意巢狀函式的使用方式。

"email@google.org" = re.replace($e.network.email.from, "com", "org")
範例 2

本範例在 replacementText 引數中使用反斜線逸出數字,參照 replaceRegex 模式的相符項目。

"test1.com.google" = re.replace(
                       $e.principal.hostname, // holds "test1.test2.google.com"
                       "test2\.([a-z]*)\.([a-z]*)",
                       "\\2.\\1"  // \\1 holds "google", \\2 holds "com"
                     )
範例 3

處理空字串和 re.replace() 時,請注意下列情況:

使用空字串做為 replaceRegex

// In the function call below, if $e.principal.hostname contains "name",
// the result is: 1n1a1m1e1, because an empty string is found next to
// every character in `stringText`.
re.replace($e.principal.hostname, "", "1")

如要取代空字串,可以使用 "^$" 做為 replaceRegex

// In the function call below, if $e.principal.hostname contains the empty
// string, "", the result is: "none".
re.replace($e.principal.hostname, "^$", "none")