tutorial 05: Regex

Welcome to this tutorial on Regular Expressions (Regex) in the context of magnetron. This is more a short example than a tutorial, just to get you started.

Regex is a powerful concept and some base knowledge is required to use it effectively. In this tutorial, you will learn how to use the following functions:

  • matchesRegEx()
  • searchRegEx()
  • replaceRegEx()

We will also introduce you to the regex flags that you can use to customize the behavior of these functions. These functions are based on the standard C++ implementation and are similar, but convenient in different situations. For more detailed information on these functions and their arguments, please refer to the documentation at /syntax/regex/.

To begin, you may want to use a previous tutorial as a base and remove the main function content, if any, and add the examples below.

Replace

In this example, we will call replaceRegEx() and print the output to the console with echo(). This function will replace all non-alphanumeric characters in the source string with a dash ('-').

echo(replaceRegEx("Quick brown fox 123", "[^A-Za-z0-9]", "-", "i"));

The first argument for replaceRegEx() is the source string. The second is the target search string with the regex specific code. The third is the string that will be used as a replacement. The fourth and last argument are the flags, separated by a semicolon. In this case, we are using the default (ECMAScript) and making it case-insensitive with "i". This last argument is also where you can specify "grep" as the commonly used grammar type. The replaceRegEx() function returns a string with the result.

Search

The searchRegEx() function returns an array with the search results. Like the replace() function, it takes a string with the target sequence to be searched for a match of the regex expression, followed by the regex pattern to match and the flags. It also takes an optional index for a specific index as an array result.

echo(objectToString(searchRegEx("Quick brown fox 123", "o", "i", 0)));

Matches

The matchesRegEx() function is purely for quick checks and returns a boolean value. The following example should return true if the source is "ab" or "cd", as indicated in the following search string separated by a '|':

echo(objectToString(matchesRegEx("ab", "ab|cd*", "i")));

This is the basic information you need to start using Regex. It is a very powerful tool for handling string data.