Working with Regex
正则表达式(缩写为 Regex)可在 Cavalry 中的多个位置使用,包括 Regex String Manipulator、Material/Style Behaviours(如 Apply Font Size)以及 JavaScript Layers。
Regex 是指定搜索模式的字符序列。Regex 的一个常见用途是匹配字符串或字符串的部分,以便对结果执行某些操作。例如,表达式 a+ 将返回输入字符串中找到的所有字母 a 的实例。因此,输入字符串 Cavalry 将返回 aa,因为它包含两个 a。
像 Regex101 这样的在线平台是学习和测试正则表达式的绝佳资源。
JavaScript Layers 使用 ECMAScript regex。
Text 和 Style Behaviours(Apply Typeface、Apply Font Size 等)使用 ICU regex,它支持 inline flags 以进行不区分大小写的匹配和其他选项。
Examples
标题为“Examples”的章节Use with the Regex String Manipulator
标题为“Use with the Regex String Manipulator”的章节Regex String Manipulator 将仅返回正则表达式的匹配结果。
| String | Regex | 描述 | Result |
|---|---|---|---|
| Hello World. | \s | 移除空格 | HelloWorld. |
| As Capably as Cavalry. | C.....y | 以 C 开头并以 y 结尾的 7 个字母的单词 | CapablyCavalry |
| Is it Colour or Color? | Colou?r | Colour 或 Color | ColourColor |
| 3 is the magic number. | \d | 任意数字 | 3 |
Use with the Style/Material Behaviours
标题为“Use with the Style/Material Behaviours”的章节Style Behaviours(Apply Typeface、Apply Font Size)和 Material Behaviours(如 Apply Text Material)使用正则表达式的结果来影响字体、外观或字符间距。
| String | Layer | Regex | 描述 | Result |
|---|---|---|---|---|
| How are you today? | Apply Typeface | \b(today)\b | 返回单词 ‘today’。 | How are you today? |
| Animate in Cavalry | Apply Text Material | \b(Cavalry)\b | 返回单词 ‘Cavalry’ | 单词 Cavalry 将使用 Fill 着色 |
Capture Groups
标题为“Capture Groups”的章节Capture Group 是一种存储和提取匹配字符串的特定部分的方法。用括号将正则表达式的部分括起来可以创建 Groups,然后可以通过在 Capture Group Indices Attribute 中输入它们的 Id 来过滤。
例如,给定字符串 hello@cavalry.studio,可以使用以下正则表达式来分隔名称、域名和顶级域名 — \b(\w+)@(\w+)\.(\w+)\b。
这将保存以下索引设置的 Capture Groups:
| Index | Contents |
|---|---|
| 1 | hello |
| 2 | cavalry |
| 3 | studio |
然后可以通过在 Capture Group Indices Attribute 中输入它们的 Id 来使用这些 Capture Groups。例如,在选择了粗体字体的 Apply Typeface 中输入 2,将导致 — hello@scenegroup.co。或者,将 Capture Group Indices 设置为 1,3 将导致 — hello@scenegroup.co。
输入值 0 或将 Capture Group Indices Attribute 留空将返回完整匹配。
Inline Flags
标题为“Inline Flags”的章节Inline flags 通过将标志放在表达式的开头来修改 regex 引擎匹配模式的方式。这些 flags 在所有 Style 和 Material Behaviours 中均受支持。
| Flag | 名称 | 描述 | Example |
|---|---|---|---|
(?i) | Case Insensitive | 无论大小写都进行匹配 | (?i)hello 匹配 “Hello”、“HELLO”、“hello” |
(?m) | Multiline | ^ 和 $ 在行边界匹配,而不仅仅是字符串的开始/结束 | (?m)^Line 匹配任何行开头的 “Line” |
(?s) | Dot All | . 匹配换行符以及其他字符 | (?s)a.b 匹配 “a”、换行符、“b” |
(?x) | Comments | 允许在模式中使用空格和注释以提高可读性 | 对于复杂模式很有用 |
Flags 可以组合:(?im) 同时启用不区分大小写和多行模式。
Example
标题为“Example”的章节| String | Regex | Result |
|---|---|---|
| Typography is important. Good typography matters. | (?i)(\btypography\b) | Typography is important. Good typography matters. |