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")