Creating Flexible Compositions with Match()

If there’s anything we know for sure by now, it is that change is a constant. That’s why the match() method is another important expression tool to add to our toolbox.

Let’s look at this example:

We have a composition with 1) a big circle and 2) a text element. We can change the text to reflect who the person is. For example, Chrysippus is a plumber/philosopher.

Here, I’ve configured the identity (plumber/philospher) to match the size of the circle. So if Chrysippus is a plumber, the green circle will be at 100% scale. However, if he’s a philosopher, the circle will be at 200% scale.

I’ve used this code for the Scale property of the circle shape layer:

var string = thisComp.layer("occupation").text.sourceText;
var regex = /philosopher/;
var result = string.match(regex);
var scale = transform.scale[0];


if (result) {
scale = 200;
} else {
100;
}


[scale, scale]

The key area to modify is the variable regex that I’ve set up. Regex is shorthand for regular expression. The regular expression is where we define a pattern to search for in a string. Even though we’re searching for things in a string, quote marks are not required. Instead, we define whatever we’re searching for between two forward slashes.

var regex = /philosopher/;

This is a simple search. But we can also define a more complex pattern by adding operators.

OR operator:

/plumber|philosopher/

Global operator: This will search for any instances of plumber:

/plumber/g;

Ignore case operator: This will search for any instances of plumber, and is not case sensitive (e.g., plumber, Plumber, plumBER.)

/plumber/i;

Combine the global and ignore case operators:

/plumber/gi;

So here’s how we can translate the bolded piece of code below into plain English: Search for any instances of philosopher in the “occupation” text layer. We attach the match() function after the variable string, and use the regex parameter that I’ve defined. The result will be “philosopher” if my text indeed has an instance of philosopher. Otherwise, the return value will be null.

var string = thisComp.layer("occupation").text.sourceText;
var regex = /philosopher/;
var result = string.match(regex);

Done! Now read more about the match() function here.