This post is part of a series on Regular Expressions and their applications in the Shortcuts app.
Using regular expressions in shortcuts is pretty simple. The Match Text block will always treat the text to match as a regular expression, and the Replace Text block has an option to treat the text to replace as a regular expression.
In the above image, the Match Text block takes the directory contents list, which looks like this:
hugo-files/data/links/cars.json hugo-files/data/links/podcasts.json hugo-files/data/links/language.json hugo-files/data/links/apps.json hugo-files/data/links/security.json hugo-files/data/links/linux.json hugo-files/data/links/programming.json hugo-files/data/links/apple.json
And performs a match to grab just the file name without the file extension, using the regular expression I talked about in previous posts.
You may notice the regular expression in the Match Text block has a little extra syntax at the beginning:
By default, ^ will match the beginning of a file or complete block of text, and $ will match the end of a file or complete block of text. In order to make them match the beginning and end of a single line of text instead, the m flag option is used.
Flag options in regular expressions are used to modify how the regular expression functions, such as how it interprets whitespace, case sensitivity, and (obviously) characters like ^ and $.
In shortcuts, flag options are put at the front of regular expressions. If you want the flag to apply to the entire regular expressions, you can use either of the following syntax methods for flag options:
The difference is that technically the first method is usually used if you want the flag to apply to the following part of the regular expression. For example you’d place it in the middle of a regular expression and it would apply to all the following. The second method always applies to the entire enclosed regular expression.
Using regular expressions in a Replace Text block is slightly different. Replace Text can be used with regular expressions or with a literal block of text which doesn’t function as a regular expression. In order to make the replace text function as a regular expression, you have to tap the “Show More” indicator and enable the Regular Expression option.
In the example above, I’m replacing the title of the post from the top of the iA Writer document with nothing (effectively removing it). This is because obviously once the post leaves iA Writer and goes onto the site, the post title is not part of the post itself.
There’s a little more to regular expressions with shortcuts that relates to matching groups that I’ll explain at a later date. You can use them to both extract the exact bit of information you need as well as to construct text from various pieces of regular expression matches in a very powerful way.