re.replace
re.replace(stringText, replaceRegex, replacementText)
說明
執行規則運算式取代作業。
這個函式需要三個引數:
stringText:原始字串。replaceRegex:表示要搜尋模式的規則運算式。replacementText:要插入每個相符項目的文字。
傳回衍生自原始 stringText 的新字串,其中與 replaceRegex 中模式相符的所有子字串,都會替換為 replacementText 中的值。您可以在 replacementText 中使用反斜線逸出的數字 (\1 至 \9),插入與 replaceRegex 模式中相應括號群組相符的文字。使用 \0 參照整個相符文字。
函式會取代不重疊的相符項目,並優先取代找到的第一個相符項目。舉例來說,re.replace("banana", "ana", "111") 會傳回字串「b111na」。
參數資料類型
STRING、STRING、STRING
傳回類型
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")