Skip to content

Regular expressions

Ayooluwa Isaiah edited this page Jul 8, 2024 · 8 revisions

F2 uses regular expressions (regex) to find matches that should be replaced. There's a string-literal mode that can be used for basic find and replace tasks, but regex mode is the default. F2 uses Go’s regex engine which is the RE2 syntax standards also used by other languages like Python, C, and Perl. With regular expressions, you can may match once, several times, or not at all for a given string. By default, it matches all occurrences but this can be configured through the -l or --limit option.

Here's a few basic examples:

Regex Explanation
.* Match all the text in the file name
^log Match text that starts with log
jpg$ Match files that end with jpg
^\d+.*png$ Match files that start with a number and ends with png
[^a-zA-Z0-9] Match any character in the filename that is not a letter or a number
\((.*?)\) Match a pair of parenthesis and everything inside

Capture variables

F2 also supports capture variables. This allows you to extract a portion of the file name for use in the replacement string:

Regex Replacement Explanation
(.*).png img_$1.png $1 will be replaced with whatever was matched by .*. E.g: fun.png becomes img_fun.png
(.*).png ${1}_img.png ${1} will be replaced with whatever was matched by .*. E.g: fun.png becomes fun_img.png
(\d\d\d\d)-(\d\d)-(\d\d) $3-$2-$1 Swap the numbers in the file name. E.g: 2020-08-07 becomes 07-08-2020

Notes on appending letters, digits, or underscores to a capture variable

Go uses $name or ${name} to represent capture variables where name is a non-empty sequence of letters, digits, and underscores.

When you use something like $1, it refers to the submatch at index 1. When you use $1_, it tries to find a variable named 1_ that was captured like this (?P<1_>...). If this variable does not exist, you will see an empty string.

To retain the use of indexes ($1) while appending letters, other digits, or underscores to the captured variable, you need to use the full syntax: ${1}_.

Please see the Expand docs to learn more!

Resources for learning regular expressions