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. |