extract()extract()

从文本字符串中获取正则表达式的匹配项。Get a match for a regular expression from a text string.

(可选)将提取的子字符串转换为指明的类型。Optionally, convert the extracted substring to the indicated type.

extract("x=([0-9.]+)", 1, "hello x=45.6|wo") == "45.6"

语法Syntax

extract(regex, captureGroup, text [, typeLiteral])extract(regex, captureGroup, text [, typeLiteral])

参数Arguments

  • regex:一个正则表达式regex: A regular expression.
  • captureGroup:一个正 int 常数,指示待提取的捕获组。captureGroup: A positive int constant indicating the capture group to extract. 0 代表整个匹配项,1 代表正则表达式中第一个“(括号)”匹配的值,2 及以上数字代表后续括号。0 stands for the entire match, 1 for the value matched by the first '('parenthesis')' in the regular expression, 2 or more for subsequent parentheses.
  • text:要搜索的 stringtext: A string to search.
  • typeLiteral:可选的类型文本(例如 typeof(long))。typeLiteral: An optional type literal (e.g., typeof(long)). (如果支持)提取的子字符串将转换成此类型。If provided, the extracted substring is converted to this type.

返回Returns

如果 regextext 中查找匹配项:与指定捕获组 captureGroup 匹配的子字符串可转换为 typeLiteral(可选)。If regex finds a match in text: the substring matched against the indicated capture group captureGroup, optionally converted to typeLiteral.

如果没有匹配项,或类型转换失败:nullIf there's no match, or the type conversion fails: null.

示例Examples

示例字符串 Trace 用于搜索 Duration 的定义。The example string Trace is searched for a definition for Duration. 匹配项转换为 real,并乘以时间常量 (1s),以便 Duration 属于 timespan 类型。The match is converted to real, then multiplied it by a time constant (1s) so that Duration is of type timespan. 在此示例中,此值等于 123.45 秒:In this example, it is equal to 123.45 seconds:

...
| extend Trace="A=1, B=2, Duration=123.45, ..."
| extend Duration = extract("Duration=([0-9.]+)", 1, Trace, typeof(real)) * time(1s) 

此示例等效于 substring(Text, 2, 4)This example is equivalent to substring(Text, 2, 4):

extract("^.{2,2}(.{4,4})", 1, Text)