KScript 文档
ZH

regex 的字段与方法

字段是关于值的一个普通事实,用点号读取,不需要方括号:$value.name。方法会接收参数或执行操作,调用方式为 ->:$value->name(arguments),也可以把值通过管道传入:$value |> name(arguments)。

字段

字段类型说明
.flagsstring标志,例如 i。
.patternstring模式,不含斜杠或标志。

来自 KScript.Core

#regex->match(text: string) → map

第一个匹配项:{ text, index, groups, captures },其中 groups 保存命名分组 (?<name>...),captures 保存编号分组。如果没有匹配则为 null。
参数接受
text 必需string
示例
<echo>{ /(\d{4})-(\d\d)/->match('Due 2026-11').groups }</echo>
echo /(\d{4})-(\d\d)/->match('Due 2026-11').groups

#regex->match_all(text: string) → list

每个匹配项,以 { text, index, groups, captures } 映射形式返回。
参数接受
text 必需string
示例
<echo>{ /\d+/->match_all('3 cats, 12 dogs')->map(fn(m) => $m.text) }</echo>
echo /\d+/->match_all('3 cats, 12 dogs')->map(fn(m) => $m.text)

#regex->replace(text: string, with) → string

The text with every match replaced. with is text, where $1 and $ are groups, or fn(match) returning text.

参数接受
text 必需string
with 必需任意值

参数可以使用命名方式:->replace(…, with: …)。

示例
<echo>{ /(\d{4})-(\d\d)/->replace('2026-11', '$2/$1') }</echo>
echo /(\d{4})-(\d\d)/->replace('2026-11', '$2/$1')

#regex->split(text: string) → list

在每个匹配处切分文本。
参数接受
text 必需string
示例
<echo>{ /\s*[,;]\s*/->split('tea, coffee;milk') }</echo>
echo /\s*[,;]\s*/->split('tea, coffee;milk')

#regex->test(text: string) → bool

当文本在某处匹配时为 true(使用 ^ 和 $ 匹配整个文本)。
参数接受
text 必需string
示例
<echo>{ /^[a-z]+$/i->test('Hello') }</echo>
echo /^[a-z]+$/i->test('Hello')

来自 any 的方法

来自 string 的方法