Working with Regex
Intro
Regular Expressions (shortened to Regex) can be used in various places in Cavalry including the Regex String Manipulator, Material/Style Behaviours like Apply Font Size and the JavaScript Layers.
Regex is a sequence of characters that specify a search pattern. A common use for regex is to match strings or parts of strings in order to do something with the result. For example, the expression a+
will return all instances of the letters a found within the input string. So an input string of Cavalry
would return aa
because it contains two a
s.
Online platforms like Regex101 are a great resource for learning and testing regular expressions.
Cavalry supports ECMAScript regex.
Examples
Use with the Regex String Manipulator
The Regex String Manipulator will return only the result of the regular expression.
String | Regex | Description | Result |
---|---|---|---|
Hello World. | \s | Remove Spaces | HelloWorld. |
As Capably as Cavalry. | C.....y | 7 letter words that start with C and end with y | CapablyCavalry |
Is it Colour or Color? | Colou?r | Colour or Color | ColourColor |
3 is the magic number. | \d | Any number | 3 |
Use with the Style/Material Behaviours
Style Behaviours (Apply Typeface, Apply Font Size and Material Behaviours like Apply Text Material) use the result of the regular expression to affect the font, appearance or character spacing.
String | Layer | Regex | Description | Result |
---|---|---|---|---|
How are you today? | Apply Typeface | \b(today)\b | Return the word 'today'. | How are you today? |
Animate in Cavalry | Apply Text Material | \b(Cavalry)\b | Return the word 'Cavalry' | The word Cavalry will be colored with the Fill |
Capture Groups
A capture group is a way to store and extract specific parts of the string being matched. Wrapping parts of a regular expression in parentheses creates groups which can then be filtered by entering their Ids into the Capture Group Indices attribute.
For example, given the string hello@scenegroup.co
, the following regular expression can be used to separate the name, domain and top level domain - \b(\w+)@(\w+)\.(\w+)\b
.
This will save capture groups with their indices set as follows:
Index | Contents |
---|---|
1 | hello |
2 | scenegroup |
3 | co |
The capture groups can then be used by entering their Ids into the Capture Group Indices attribute. For example, entering 2
to an Apply Typeface where a bold typeface is selected would result in - hello@scenegroup.co. Alternatively, setting Capture Group Indices of 1,3
would result in - hello@scenegroup.co.
Entering a value of 0
or leaving the Capture Group Indices attribute empty will return the full match.