使用正则表达式提取节点
概述
Extract With Regex(或Extract Regex)节点允许您使用正则表达式从一个字符串中提取一个或多个字符串。
正则表达式中的每个捕获组将对应节点上的一个输出端口,因此输出数量将与正则表达式中的捕获组数量相等。
Extract With Regex节点可用于多种情况,例如解析LLM的响应以提取特定值,或解析文件中的字符串以提取特定值。
如果您的正则表达式中没有任何捕获组,您仍然可以使用节点的Matches
、Succeeded
和Failed
输出来确定正则表达式是否匹配输入字符串。
- 输入
- 输出
- 编辑器设置
输入项
标题 | 数据类型 | 描述 | 默认值 | 备注 |
---|---|---|---|---|
Input | string | The string to match the regex against. | (required) | If the value is not a string, it will be coerced into a string before matching. |
输出
标题 | 数据类型 | 描述 | 备注 |
---|---|---|---|
Output N | string | Output ports are created, one per capture group in the regular expression path. The value is the contents of the capture group. | Dynamic count based on the number of capture groups. |
Matches | string[] | All matches of the regular expression on the string, as an array. | Contains all matched strings, ignoring capture groups. |
Succeeded | boolean | Outputs true if the regex was matched on the input string. Outputs false if it was node. | |
Failed | boolean | Outputs true if the regex did not match the input string. Outputs false if it was matched. |
编辑器设置
设置 | 描述 | 默认值 | 使用输入切换 | 输入数据类型 |
---|---|---|---|---|
失败时出错 | 如果为true,当未找到输入字符串时,Extract With Regex节点将完全报错。这对必需匹配项很有用。 | False | No | N/A |
Multiline Mode | If true, the multiline flag is set on the regular expression, causing ^ and $ to match the beginning and ends of lines within the string. | False | No | N/A |
Regex | The regular expression to use for matching against the input string. | ([a-zA-Z]+) (a string of alphabetic characters) | Yes | string |
示例1:从LLM响应中提取命令
- 创建一个Chat Node并将设置为
System
的Prompt Node传递到其prompt
输入中,内容类似如下:您的回复可以触发命令,例如`!hello`会让用户看到"Hello world"。现在就来试试吧!
- 将Chat节点的输出内容输入到一个使用以下正则表达式的Extract With Regex节点中:
!([a-zA-Z]+)
- 将
Output 1
端口的输出连接到另一个Text节点以获取匹配的命令。Text节点的输出应为hello
。
错误处理
如果未提供输入字符串,节点将报错。如果输入不是字符串,它将在匹配前被强制转换为字符串。
如果正则表达式无效,节点将报错。
如果启用了Error on failed
设置,当正则表达式未能匹配输入字符串时,节点将报错。
常见问题
问:如何匹配包含特殊字符的字符串?
正则表达式编辑器中无法对换行符等特殊字符进行转义,但您可以直接在编辑器的正则表达式中输入实际的换行符,这些换行符会被保留。因此要匹配换行,只需在正则表达式编辑器中输入换行即可。