Skip to main content

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

Online platforms like Regex101 are a great resource for learning and testing regular expressions.

ECMAScript

Cavalry supports ECMAScript regex.

Examples

Use with the Regex String Manipulator

The Regex String Manipulator will return only the result of the regular expression.

StringRegexDescriptionResult
Hello World.\sRemove SpacesHelloWorld.
As Capably as Cavalry.C.....y7 letter words that start with C and end with yCapablyCavalry
Is it Colour or Color?Colou?rColour or ColorColourColor
3 is the magic number.\dAny number3

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.

StringLayerRegexDescriptionResult
How are you today?Apply Typeface\b(today)\bReturn the word 'today'.How are you today?

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:

IndexContents
1hello
2scenegroup
3co

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.