跳到內容

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 TypefaceApply Font Size 等)使用 ICU regex,它支援 inline flags 以進行不區分大小寫的匹配和其他選項。

Regex String Manipulator 將僅返回正規表達式的匹配結果。

StringRegex描述Result
Hello World.\s移除空格HelloWorld.
As Capably as Cavalry.C.....yC 開頭並以 y 結尾的 7 個字母的單詞CapablyCavalry
Is it Colour or Color?Colou?rColour 或 ColorColourColor
3 is the magic number.\d任意數字3

Style Behaviours(Apply TypefaceApply Font Size)和 Material Behaviours(如 Apply Text Material)使用正規表達式的結果來影響字型、外觀或字元間距。

StringLayerRegex描述Result
How are you today?Apply Typeface\b(today)\b返回單詞 ‘today’。How are you today?
Animate in CavalryApply Text Material\b(Cavalry)\b返回單詞 ‘Cavalry’單詞 Cavalry 將使用 Fill 著色

Capture Group 是一種儲存和提取匹配字串的特定部分的方法。用括號將正規表達式的部分括起來可以建立 Groups,然後可以透過在 Capture Group Indices Attribute 中輸入它們的 Id 來過濾。

例如,給定字串 hello@cavalry.studio,可以使用以下正規表達式來分隔名稱、域名和頂級域名 — \b(\w+)@(\w+)\.(\w+)\b

這將儲存以下索引設定的 Capture Groups:

IndexContents
1hello
2cavalry
3studio

然後可以透過在 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 透過將標誌放在表達式的開頭來修改 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) 同時啟用不區分大小寫和多行模式。

StringRegexResult
Typography is important. Good typography matters.(?i)(\btypography\b)Typography is important. Good typography matters.