[comment]: # translation:outdated

[comment]: # ({4151d28b-4151d28b})
# 12 正则表达式

[comment]: # ({/4151d28b-4151d28b})

[comment]: # ({17ed5ab5-17ed5ab5})
#### 概述

[Perl Compatible Regular
Expressions](https://en.wikipedia.org/wiki/Perl_Compatible_Regular_Expressions)
(PCRE, PCRE2) 在Zabbix中得到支持。

在Zabbix中使用正则表达式有两种方式：

-   手动输入正则表达式
-   使用在Zabbix中创建的全局正则表达式

[comment]: # ({/17ed5ab5-17ed5ab5})

[comment]: # ({8e3db97d-439895e1})
#### 正则表达式

您可以在支持的位置手动输入正则表达式。请注意
表达式不能以@开头，因为该符号在Zabbix中
用于引用全局正则表达式。

::: notewarning
使用正则表达式时可能会run栈溢出。详情请参阅
[pcrestack man
page](http://pcre.org/original/doc/html/pcrestack.html)获取更多信息。

:::

请注意在多行匹配中，`^`和`$`锚点分别匹配
每行的开头/结尾，而不是整个string的
开头/结尾。

另请参阅[correct escaping](/manual/appendix/escaping)在不同上下文中的使用示例。

[comment]: # ({/8e3db97d-439895e1})

[comment]: # ({2e290e3b-e24754dc})
#### 全局正则表达式

Zabbix前端提供了一个高级编辑器用于创建和测试复杂的正则表达式。

通过这种方式创建正则表达式后，可以在前端多个位置通过引用其名称（前缀为@符号）来使用，例如*\@mycustomregexp*。

要create全局正则表达式：

-   进入：*管理 → 常规*
-   从下拉菜单中选择*正则表达式*
-   点击*新建正则表达式*

**表达式**选项卡允许设置正则表达式名称并添加子表达式。

![](../../assets/en/manual/regular_expressions/global_regexp.png)

所有必填字段都标有红色星号。

| 参数 | <   | 描述 |
|-|----------|----------------------------------------|
| *Name* | <   | 设置正则表达式名称。允许使用任何Unicode字符。 |
| *Expressions* | <   | 在表达式区块点击*添加*来新增子表达式。 |
|           | *表达式类型* | 选择表达式类型：<br>**包含字符string** - 匹配子字符串<br>**包含任意字符string** - 匹配分隔列表中的任意子字符串。分隔列表包含逗号(,)、点(.)或正斜杠(/)。<br>**不包含字符string** - 匹配除子字符串外的任何string<br>**结果为TRUE** - 匹配正则表达式<br>**结果为FALSE** - 不匹配正则表达式 |
| ^ | *表达式* | 输入子字符串/正则表达式。 |
| *Delimiter* | <   | 用于分隔正则表达式中文本字符串的逗号(,)、点(.)或正斜杠(/)。此参数仅在选择"*包含任意字符string*"表达式类型时激活。 |
| *Case sensitive* | <   | 复选框，用于指定正则表达式是否区分字母大小写。 |

表达式中的正斜杠(/)会被视为字面量而非分隔符。这样可以保存包含斜杠的表达式而不会报错。

::: noteimportant
Zabbix中的自定义正则表达式名称可以
包含逗号、空格等字符。在可能引起引用歧义的情况下（例如监控项键参数中的逗号），
整个引用可以用引号包裹，如：*"\@My custom regexp for purpose1, purpose2"*。\
正则表达式名称在其他位置（例如LLD规则属性中）不得加引号。

:::

在**测试**选项卡中，可以通过提供测试string来测试正则表达式及其子表达式。

![](../../assets/en/manual/regular_expressions/global_regexp_b.png)

测试结果会显示每个子表达式的状态以及自定义表达式的总体状态。

自定义表达式的总体状态显示为*组合结果*。如果定义了多个子表达式，Zabbix会使用AND逻辑运算符计算*组合结果*。这意味着只要有一个子表达式结果为False，*组合结果*也将为False状态。

[comment]: # ({/2e290e3b-e24754dc})

[comment]: # ({ffa7eed6-2ea2d961})
#### 默认全局正则表达式

Zabbix默认数据集包含多个全局正则表达式。

| 名称 | 表达式 | 匹配项 |
|--|------|------|
| *File systems for discovery* | `^(btrfs|ext2|ext3|ext4|jfs|reiser|xfs|ffs|ufs|jfs|jfs2|vxfs|hfs|refs|apfs|ntfs|fat32|zfs)$` | "btrfs" 或 "ext2" 或 "ext3" 或 "ext4" 或 "jfs" 或 "reiser" 或 "xfs" 或 "ffs" 或 "ufs" 或 "jfs" 或 "jfs2" 或 "vxfs" 或 "hfs" 或 "refs" 或 "apfs" 或 "ntfs" 或 "fat32" 或 "zfs" |
| *Network interfaces for discovery* | `^Software Loopback Interface` | 以"Software Loopback Interface"开头的字符串 |
|      | `^lo$` | "lo"    |
|      | `^(In)?[Ll]oop[Bb]ack[0-9._]*$` | 可选以"In"开头，后接"L"或"l"，然后是"oop"，接着"B"或"b"，再接"ack"，最后可跟任意数量的数字、点或下划线 |
|      | `^NULL[0-9.]*$` | 以"NULL"开头，可选后接任意数量数字或点的字符串 |
|      | `^[Ll]o[0-9.]*$` | 以"Lo"或"lo"开头，可选后接任意数量数字或点的字符串 |
|      | `^[Ss]ystem$` | "System" 或 "system" |
|      | `^Nu[0-9.]*$` | 以"Nu"开头，可选后接任意数量数字或点的字符串 |
| *Storage devices for SNMP discovery* | `^(Physical memory|Virtual memory|Memory buffers|Cached memory|Swap space)$` | "Physical memory" 或 "Virtual memory" 或 "Memory buffers" 或 "Cached memory" 或 "Swap space" |
| *Windows service names for discovery* | `^(MMCSS|gupdate|SysmonLog|clr_optimization_v2.0.50727_32|clr_optimization_v4.0.30319_32)$` | "MMCSS" 或 "gupdate" 或 "SysmonLog" 或类似"clr\_optimization\_v2.0.50727\_32"和"clr\_optimization\_v4.0.30319\_32"的字符串（其中点可替换为除换行符外的任意字符） |
| *Windows service startup states for discovery* | `^(automatic|automatic delayed)$` | "automatic" 或 "automatic delayed" |

[comment]: # ({/ffa7eed6-2ea2d961})

[comment]: # ({4c860844-4c860844})
#### 示例

[comment]: # ({/4c860844-4c860844})

[comment]: # ({eb858ac0-eb858ac0})
##### 示例1

在低级发现中使用以下表达式来发现除特定名称数据库之外的所有数据库:

    ^TESTDATABASE$

![regexp\_expr\_2.png](../../assets/en/manual/regular_expressions/regexp_expr_2.png)

选择的*表达式类型*: "结果为FALSE"。不匹配包含string "*TESTDATABASE*"的名称。

[comment]: # ({/eb858ac0-eb858ac0})

[comment]: # ({be96a07d-be96a07d})
##### 带内联正则修饰符的示例

使用包含内联修饰符(?i)的以下正则表达式
来匹配字符"error":

    (?i)error

![regexp\_expr\_3a.png](../../assets/en/manual/regular_expressions/regexp_expr_3a.png)

选择的*表达式类型*: "结果为TRUE"。字符"error"被
匹配。

[comment]: # ({/be96a07d-be96a07d})

[comment]: # ({489130e5-489130e5})
##### 另一个使用内联正则修饰符的示例

使用包含多个行内修饰符的以下正则表达式来匹配特定行之后的字符：

    (?<=match (?i)everything(?-i) after this line\n)(?sx).*# we add s modifier to allow . match newline characters

![regexp\_expr\_4\_new.png](../../assets/en/manual/regular_expressions/regexp_expr_4_new.png)

选择的表达式类型："结果为TRUE"。匹配特定行之后的字符。

::: noteimportant
 **g** 修饰符不能在行内指定。可用的修饰符列表可在[pcresyntax man
page](https://www.pcre.org/original/doc/html/pcresyntax.html#SEC16)中找到。有关PCRE语法的更多信息，请参阅[PCRE HTML
documentation](https://www.pcre.org/original/doc/html/pcrepattern.html)。

:::

[comment]: # ({/489130e5-489130e5})

[comment]: # ({ae319bc1-56f9b2c2})
#### 按位置支持的正则表达式

| 位置 | <   | 正则表达式 | 全局正则表达式 | 多行匹配 | 注释 |
|-|----------|---------|---------|---------|--------------------|
| **[Agent items](/manual/config/items/itemtypes/zabbix_agent)** | <   | <                  | <                         | <                  | <        |
| <        | eventlog\[\] | 是                | 是                       | 是                | `regexp`, `severity`, `source`, `eventid` 参数 |
| ^        | log\[\] | ^                  | ^                         | ^                  | `regexp` 参数 |
| ^        | log.count\[\] | ^                  | ^                         | ^                  | ^        |
| ^        | logrt\[\] | ^                  | 是/否                    | ^                  | `regexp` 参数支持两者，`file_regexp` 参数仅支持非全局表达式 |
|^|logrt.count\[\]|^|^|^|^

| ^   | proc.cpu.util\[\] | ^   | 否  | 否  | `cmdline` 参数 |
| ^   | proc.mem\[\]      | ^   | ^   | ^   | ^          |
| ^   | proc.num\[\]                  | ^   | ^   | ^   | ^          |
| ^   | sensor\[\]                    | ^   | ^   | ^   | `device` and `sensor` parameters on Linux 2.4          |
| ^   | system.hw.macaddr\[\]         | ^   | ^   | ^   | `interface` parameter          |
| ^   | system.sw.packages\[\]        | ^   | ^   | ^   | `package` parameter          |
| ^   | vfs.dir.count\[\]             | ^   | ^   | ^   | `regex_incl`, `regex_excl`, `regex_excl_dir` parameters          |
| ^   | vfs.dir.get\[\]   | ^   | ^   | ^   | `regex_incl`, `regex_excl`, `regex_excl_dir` parameters          |
| ^   | vfs.dir.size\[\]              | ^   | ^   | ^   | `regex_incl`, `regex_excl`, `regex_excl_dir` parameters          |
| ^   | vfs.file.regexp\[\] | ^   | ^   | 是 | `regexp` parameter          |
| ^   | vfs.file.regmatch\[\] | ^   | ^   | ^   | ^          |
| ^   | web.page.regexp\[\]           | ^   | ^   | ^   | ^          |
| **[SNMP traps](/manual/config/items/itemtypes/snmptrap)** | <                             | <   | <   | <   | <          |
| <   | snmptrap\[\]                  | 是 | 是 | 否  | `regexp` parameter          |
| **[监控项-值预处理](/manual/config/items/item#监控项-值预处理)** | <                             | 是 | 否  | 否  | `pattern` parameter          |
| **[Functions for triggers/calculated items](/manual/appendix/functions)** | <                             | <   | <   | <   | <          |
| <   | count()                       | 是 | 是 | 是 | `pattern` parameter if `operator` parameter is *regexp* or *iregexp*          |
| <   | countunique()                 | 是 | 是 | ^   | ^          |
| <   | find()                        | 是 | 是 | ^   | ^          |
| ^   | logeventid()                  | 是 | 是 | 否  | `pattern` parameter          |
| ^   | logsource()                   | ^   | ^   | ^   | ^          |
| **[过滤器](/manual/discovery/low_level_discovery#过滤器)** | <                             | <   | <   | <   | <          |
| <   | 过滤器                       | 是 | 是 | 否  | *Regular expression* field          |
| ^   | 覆盖项                       | 是 | 否  | ^   | In *matches*, *does not match* options for *Operation* conditions          |
| **[Action conditions](/manual/config/notifications/action/conditions)** | <                             | 是 | 否  | 否  | In *matches*, *does not match* options for *Host name* and *Host metadata* autoregistration conditions          |
| **[配置web场景](/manual/web_monitoring#配置web场景)** | <                             | 是 | 否  | 是 | *Variables* with a **regex:** prefix<br>*Required string* field          |
| **[用户宏上下文](/manual/config/macros/user_macros#用户宏上下文)** | <                             | 是 | 否  | 否  | In macro context with a **regex:** prefix          |
| **[Macro functions](/manual/config/macros/macro_functions)** | <                             | <   | <   | <   | <          |
| <   | regsub()                      | 是 | 否  | 否  | `pattern` parameter          |
| ^   | iregsub()                     | ^   | ^   | ^   | ^          |
| **[图标映射](/manual/web_interface/frontend_sections/administration/general#图标映射)** | <                             | 是 | 是 | 否  | *Expression* field          |
| **[配置](/manual/config/items/mapping#配置)** | <                             | 是 | 否  | 否  | *Value* field if mapping type is `regexp`          |

[comment]: # ({/ae319bc1-56f9b2c2})
