Skip to content

Regular expressions

Ayooluwa Isaiah edited this page Feb 2, 2023 · 9 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

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

Resources for learning regular expressions

Clone this wiki locally