Formula Reference
The Blaze Formula Language makes it possible to use formulas and calculations as part of your snippets.
This enables dynamic snippet content.
The Blaze Formula Language is used in the {=} (Formula Command), {if} and {repeat} commands.
There's a lot of functionality built-in to help you truly make snippets your own.
This page will cover everything you need to know about the Blaze Formula Language and includes a variety of examples.
50% More Would Be: {=count * 1.5} {if: count > 10}That's a lot!{else}Not so many.{endif}
Supported Values
The Blaze Formula Language supports five types of values:
- Numbers (e.g.
12
,3.75
, or-10
) - Booleans (
yes
orno
) - Text Strings (e.g
"abc"
or"this is a string"
) - Lists (e.g.
[1, 2, "three", yes]
) - Functions (e.g.
(x) -> x * 2
)
Throughout this documentation page, you'll learn that the Blaze Formula Language primarily consists of working with and manipulating these core supported values.
Text Blaze will convert between these different types as needed. For example, let's look at the max()
function which takes two or more numbers and returns the largest one of them. If you pass a string to the max()
function, it will attempt to convert the string to a number automatically. For example, max(2, "3", 1)
would return the number 3.
You'll learn about those, but before that, we'll review a very important concept within your snippets: Creating Variables.
Creating Variables
Text Blaze allows you to create variables to reference values in your snippets. There are several ways to create variables in your snippets:
- The {=} (Formula Command) command provides an assignment mode that allows you to create a variable.
- Forms commands allows you to use the
name
setting to explicitly give a form value a variable name.
{num=12} {bool=yes} {str="this is a string"} {`Multi word variable name`="variable names can be multiple words"}
{formtext: name=firstname; default=John}
num: {=num} firstname: {=firstname} str: {=str} bool: {=bool} Multi word variable names: {=`multi word variable name`}
Variable names are case-insenstive, so "address" and "Address" refer to the same thing. Regular variable names start with a letter which is followed by any combination of letters, numbers and underscores. You can create variable names that include spaces or other special characters, however you must enclose those variable names in back ticks ` when referencing them in your formulas.
Creating variables and saving data becomes important as you use the various features of the Blaze Formula Language.
Lists
Lists are a value type that can hold more than one value at a time. They are wrapped in brackets ([]
) with each value being separated by a comma (,
).
There are two types of lists in Text Blaze: ordered lists and keyed lists.
Ordered Lists
Ordered lists are a set of one or more values.
For example, ["Hi"]
or ["Hi", "Hello", ...]
. A list can also be empty and contain no values (e.g. []
).
A list can contain values of any type (e.g. [1, 2, "three", yes]
), but the most common use case is multiple values of the same type (e.g. ["Katie", "John", "Greg"]
).
Accessing Items In Ordered Lists
Since there is a distinct order to the items in the list, you can access a specific item by its index
using the syntax list[index]
.
An index is the position of the element in the list. The first element in the list has index 1, the second index 2 and so on. For example:
Ordered lists are especially useful when processing multiple items of a specific type.
Keyed Lists
Keyed lists, the second type of list, are a set of key-value pairings. Their syntax is as follows:
["key a": ValueA, "key b": ValueB, ...]
Keys are case-sensitive.
Also, unlike ordered lists, there is no ordering to the keys or values in keyed lists.
Accessing Items In Keyed Lists
You can access individual elements using the syntax list.key
. For example:
The "." syntax to reference a value in a keyed list doesn't work when the key has spaces or other special characters in it.
To access values in this case you can use the ["key a"]
syntax. You can also use this syntax to reference values that don't contain any spaces or special characters, similar to the "." syntax (e.g. ["color"]
).
While this syntax may look similar to the way values are referenced in ordered lists, notice how a string is used instead of a number because you're not referencing a position in the list.
If the key is not quoted when defining a list, it is a treated as a variable and the value of the variable is used as the key value. The following example illustrates this:
{=list["abc"]}
Later on this documentation page, you'll learn about a variety of useful built-in functions that work on lists.
Functions
A function is similar to a built-in function except it does not have a name.
The syntax for a function is:
(arg1, arg2, ...) -> doSomething(arg1, arg2, ...)
A function is treated as a value in Text Blaze. This means three things:
- Built-in functions can take functions as an argument, just like a Number, Text String, or any other value.
- Some command settings can receive a function as a value.
- You can assign a function to a variable using the {=} (Formula Command) command's assignment mode.
Function as an argument
The filter()
function, which allows you to filter a list takes a function to define the filtering to use. The function must return a Boolean.
The following example shows the use of functions with the filter()
built-in function to filter the same ordered list in three different ways:
Numbers equal to 5: {=filter([9, 4, 10, 1, 12], value -> value = 5)}
All even numbers {=filter([9, 4, 10, 1, 12], value -> iseven(value))}
Using a function as the argument, you can define whatever filtering method you want. Also, notice how it's possible to use built-in functions in your functions.
Functions as command settings
A function can be used as a command setting's value. For example, {formmenu} has a setting called itemformatter
that allows you to format the individual values of the menu items before snippet insertion.
Visit the {formmenu} command to learn more about its functionality.
Assign a function to a variable
Using the {=} (Formula Command)'s assignment mode, it's possible to assign a function to a variable.
Here's an example for squaring a number:
Notice how in the example above, we're creating a function and using other built-in functions within it. Functions allow you to combine operators, built-in functions, and even other functions inside of them.
Finally, we're saving that whole function to a variable and naming it squared
. Now it's possible to use this variable anywhere else in your snippet.
You can also call functions directly in the {=} (Formula Command) command by using parenthesis ()
and passing your arguments directly.
For example:
A common use case for functions is manipulating lists. The filter()
, map()
and reduce()
built-in functions are three functions for operating across a list that use functions.
Divide everything in the list by 100: {=map(n, v -> v/100)}
Get a new list that doubles all the numbers in the list. {=map(n, (val) -> val * 2)}
Supported Operators
The Blaze Formula Language supports many operators for working with the various supported values. You can manipulate numbers, compare values, work with strings, and handle boolean (yes/no) values.
Text Blaze will convert between these when suitable in formulas. If you try to use types in a way that is not supported (e.g. 12 + yes
or "abc" * 2
) an error will be shown.
Math Operators
Text Blaze provides you with a few general Math operators for working with numbers.
Operator | Description | Example |
---|---|---|
+ | Add two numbers together | 5 + 6 ⇒ 11 |
- | Subtract two numbers | 7 - 2 ⇒ 5 |
* | Multiply two numbers | 5 * 2 ⇒ 10 |
/ | Divide two numbers | 9 / 2 ⇒ 4.5 |
^ | Take a number to a power | 2 ^ 3 ⇒ 8 |
Comparison Operators
Comparison operators are very useful for comparing two values. The final result will always resolve into a Boolean (yes/no) value. You'll use these a lot when creating conditions for the {if} command.
Operator | Description | Example |
---|---|---|
= | Whether two values are equal (can convert types) | 2 = 2 ⇒ yes |
<> | Whether two values are not equal (can convert types) | 2 <> 2 ⇒ no |
>= | Greater than or equals to | 5 >= 2 ⇒ yes |
> | Greater than | 5 > 2 ⇒ yes |
<= | Less than or equals to | 5 <= 2 ⇒ no |
< | Less than | 5 < 2 ⇒ no |
{if: 2 = "2"} Yes, 2 is equal to "2". It did type conversion. {endif}
{if: 3 <= 5} Yes, 3 is less than or equal to 5. {endif}
{if: 3 <> 2} Nope, 3 is not equal to 2. {endif}
String Operators
Text Blaze provides you with one operator, the &
operator, to help you concatenate strings together.
Text Blaze provides you with plenty of string built-in functions to work with strings further.
Operator | Description | Example |
---|---|---|
& | String concatenation | "abc" & "xyz" & 1 ⇒ "abcxyz1" |
Logical Operators
These operators are very useful for working with Boolean (yes/no) values.
Operator | Description | Example |
---|---|---|
not | The opposite of a boolean | not no ⇒ yes |
and | Whether two booleans are both true | yes and no ⇒ no |
or | Whether either of two booleans is true | yes or no ⇒ yes |
ternary | Conditional value. Of the form: value1 if condition else value2 | "big" if 100 > 10 else "small" ⇒ "big" |
Built-in Functions
Besides operators that allow you to work with the various Text Blaze supported values, you also get access to built-in functions.
A built-in function is a contained piece of functionality designed to perform a particular task.
Text Blaze supports a variety of these built-in functions for you to use in your snippets.
Math Functions
Function | Description | Example |
---|---|---|
round(x) | Rounds a number to the nearest integer | round(1.7) ⇒ 2 |
floor(x) | Rounds a number down to the nearest integer | floor(1.7) ⇒ 1 |
ceil(x) | Rounds a number up to the nearest integer | ceil(1.2) ⇒ 2 |
sqrt(x) | Gets the square root of a number | sqrt(16) ⇒ 4 |
abs(x) | Gets the absolute value of a number | abs(-3) ⇒ 3 |
log(x) | Gets the base-10 log of a number | log(100) ⇒ 2 |
ln(x) | Gets the natural log of a number | ln(100) ⇒ 4.605 |
remainder(x, y) | Gets the remainder from a division | remainder(12, 5) ⇒ 2 |
max(x, y, ...) | Gets the maximum of two or more values | max(3, 7) ⇒ 7 |
min(x, y, ...) | Gets the minimum of two or more values | min(3, 7) ⇒ 3 |
isodd(x) | Whether a number is odd | isodd(7) ⇒ yes |
iseven(x) | Whether a number is even | iseven(7) ⇒ no |
random() | Gets a random number between 0 and 1 | random() ⇒ 0.370826324 |
base(x, base, padding) | Express numbers in different numeric bases (e.g. hexadecimal) | base(123, 16) ⇒ "7b" |
Trigonometric Functions
Similar to the Math functions these built-in functions are designed to help you work with trigonometry.
All of these functions take a single number as an argument and return a single number.
Function | Description | Example |
---|---|---|
sin(x) | Returns the sine of a number of degrees | sin(90) ⇒ 1 |
cos(x) | Returns the cosine of a number of degrees | cos(90) ⇒ 0 |
tan(x) | Returns the tangent of a number of degrees | tan(45) ⇒ 1 |
asin(x) | Returns the arcsine in degrees of a number | asin(1) ⇒ 90 |
acos(x) | Returns the arccosine in degrees of a number | acos(0) ⇒ 90 |
atan(x) | Returns the arctangent in degrees of a number | atan(1) ⇒ 45 |
Some of Text Blaze's trigonometric functions are approximate. Due to the numerical approaches to determine their values, there may be extremely small errors in their output (in the 10th decimal place or beyond).
For example, instead of equalling exactly 0
, cos(90)
could instead return 0.00000000000000006123
.
Because of this, you may need to round results from these functions when formatting them for output with the round()
function.
For example, you can do round(cos(90))
to get 0
.
Statistical Functions
Similar to the Math functions and Trigonometric functions these built-in functions are designed to help you work with statistics.
Function | Description | Example |
---|---|---|
average(list) | The average (mean) of the elements in a list | average([1, 4, 10]) ⇒ 5 |
median(list) | The median of the elements in a list | median([1, 4, 10]) ⇒ 4 |
stddevpop(list) | The population standard deviation of the elements in a list | stddevpop([0, 1, 4, 9]) ⇒ 3.5 |
variancepop(list) | The population variance of the elements in a list | variancepop([0, 1, 4, 9]) ⇒ 12.25 |
stddevsamp(list) | The sample standard deviation of the elements in a list | stddevsamp([1, 2, 3]) ⇒ 1 |
variancesamp(list) | The sample variance of the elements in a list | variancesamp([1, 2, 3]) ⇒ 1 |
normdist(number, mean, standard_deviation, cumulative) | Normal distribution function for a number given mean and standard deviation | normdist(0, 0, 1, yes) ⇒ 0.5 |
norminv(number, mean, standard_deviation) | Inverse normal distribution function for a number given mean and standard deviation | norminv(0.5, 0, 1) ⇒ 0 |
ztest(list, value, standard_deviation (optional)) | The one-tailed p-value of a z-test with standard distribution, i.e., the probability of the sample mean being greater than the observed value, given a population mean. If the standard deviation is not provided, the sample standard deviation will be used | ztest([1, 2, 3], 2) ⇒ 0.5 |
tdist(number, degrees_freedom, cumulative) | Left-tailed Student's t-distribution function for a number given degrees of freedom | tdist(0, 2, yes) ⇒ 0.5 |
tinv(number, degrees_freedom) | Left-tailed inverse Student's t-distribution function for a number given degrees of freedom | tinv(0.5, 1) ⇒ 0 |
ttest(list1, list2, tails, type) | The probability associated with a Student's t-test. This test determines whether two samples are likely to have come from two populations that have the same mean. It requires the type to be either "PAIRED", "HOMOSCEDASTIC" (equal variance), or "HETEROSCEDASTIC" (unequal variance) | ttest([1, 2, 3], [1, 2, 3], 1, "HOMOSCEDASTIC") ⇒ 0.5 |
Error Functions
There are often times when errors will appear in your snippets.
For example, if a form isn't validated or a function returns no value. To help you deal with these scenarios, Text Blaze provides you with two different error built-in functions.
Function | Description | Example |
---|---|---|
error(msg) | Raises a Text Blaze error | error("Invalid widget size") |
catch(x, msg) | Evaluates and returns x. If there is an error in x, returns msg. msg may also be an anonymous function taking the error as its first argument | catch(log(-1), "Negative") ⇒ "Negative" |
Text String Functions
Text Blaze provides you with built-in string functions to help you work with Text Strings.
Function | Description | Example |
---|---|---|
concat(x, y, ...) | Concatenates two or more values as a string | concat("abc", 123) ⇒ "abc123" |
lower(x) | Lowercase a string | lower("Hi") ⇒ "hi" |
upper(x) | Uppercase a string | upper("Hi") ⇒ "HI" |
left(x, count) | Leftmost characters | left("Hi all", 2) ⇒ "Hi" |
right(x, count) | Rightmost characters | right("Hi all", 2) ⇒ "ll" |
proper(x) | Capitalizes each word | proper("HI all") ⇒ "Hi All" |
trim(x) | Removes leading and trailing whitespace | trim(" abc ") ⇒ "abc" |
reverse(x) | Reverses a string | reverse("abc") ⇒ "cba" |
replace(x, find, replacement) | Replaces all occurrences of find with replacement | replace("good job", "good", "great") ⇒ "great job" |
len(x) | The length of a string in characters | len("abc") ⇒ 3 |
substring(x, start, length) | Extracts the portion of the string of length from the start character. If start is negative, it is relative to the end of the string. If length is omitted, the rest of the string is returned. | substring("abcdef", 2, 3) ⇒ "bcd" |
comparestrings(a, b) | Returns a negative number if a is lexicographically before b, a positive number if b is before a and 0 if they are equivalent. | comparestrings("at", "dog") ⇒ -1 |
contains(string, value) | Whether one string contains another | contains("Good morning", "morning") ⇒ yes |
startswith(string, value) | Whether one string starts with another | startswith("Good morning", "morning") ⇒ no |
endswith(string, value) | Whether one string ends with another | endswith("Good morning", "morning") ⇒ yes |
search(string, value) | The position of one string in another | search("Good morning", "morning") ⇒ 6 |
Regular Expression Functions
Regular Expressions are a very powerful tool to help you create search patterns.
Function | Description | Example |
---|---|---|
testregex(x, regex, flags) | Tests whether a regular expression matches a string | testregex("dog", "d..") ⇒ yes |
extractregex(x, regex, flags) | Extracts the portion of a string matching a regular expression. If a capture group is set, extracts the capture group | extractregex("dog", "d(..)") ⇒ "og" |
extractregexall(x, regex, flags) | Like extractregex , but gets all the matches rather than just the first | extractregexall("dog den", "d(..)") ⇒ ["og", "en"] |
splitregex(x, regex, flags) | Splits a string by a regular expression | splitregex("ab5cd3ef", "\d") ⇒ ["ab", "cd", "ef"] |
replaceregex(x, regex, replacement, flags) | Replaces matches of a regular expression in a string | replaceregex("ID: 1234", "\d", "X", "g") ⇒ "ID: XXXX" |
{extractedemail=extractregex("Email: john.example@example.com", "\w+@[.\w]+\b")}
Extracted Email: {=extractedemail}
{if: testregex("Is this a question?", ".+?")} Yes, this RegEx tests whether a string ends with a question mark. {endif}
Supported flags
In all the above regex functions, flags is an optional argument. It can be set to a string containing any of these characters:
- When the ignore case flag (
"i"
) is set, the search will be case-insensitive. - When the multi-line flag (
"s"
) is set, the "." special character will match multiple lines. - The global flag (
"g"
) is only supported inreplaceregex
. When it is set, the search will replace all matches instead of only the first match.
Here's an example using the multi-line and ignore-case flags ("is"
):
Date Time Functions
These functions do calculations based on date and times. Other than datetimeparse
, these functions require the date to be in the format YYYY-MM-DD
or YYYY-MM-DD HH:MM:SS
. datetimeparse
can be used to convert a date to that format.
Function | Description | Example |
---|---|---|
datetimeparse(date, format) | Parse a date | datetimeparse("Jan 23, 2020", "MMM D, YYYY") ⇒ 2020-01-23 |
datetimeformat(date, format) | Format a date | datetimeformat("2020-01-23", "MMM D, YYYY") ⇒ Jan 23, 2020 |
datetimeadd(date, amount, units) | Adds time to a date | datetimeadd("2020-01-23", 9, "D") ⇒ 2020-02-01 |
datetimediff(date, date, units) | Finds the difference between two dates | datetimediff("2020-01-23", "2020-02-01", "D") ⇒ 9 |
List Functions
These functions work on both ordered lists and keyed lists.
The output of these functions depends on which function you choose. Some functions return lists, others a Boolean (yes/no) value, or a number.
Function | Description | Example |
---|---|---|
count(list) | The number of elements in a list | count([1, 4, 9]) ⇒ 3 |
includes(list, value) | yes if a list contains a specific value | includes([1, 4, 9], 4) ⇒ yes |
location(list, value) | Returns the index or key of the first location of the value | location([1, 4, 9], 4) ⇒ 2 |
merge(list, list2, ...) | Merges two or more lists together | merge([1], [2, 3], [4]) ⇒ [1, 2, 3, 4] |
filter(list, fn(value, index/key)) | Returns a new list comprised of the elements where fn evaluates to yes | filter([1, 4, 9], v -> v > 3) ⇒ [4, 9] |
map(list, fn(value, index/key)) | Returns a new list where each element is replaced with the value of fn | map([1, 4, 9], v -> v > 3) ⇒ [no, yes, yes] |
reduce(list, accumulator, fn(accumulator, value, index/key)) | Aggregates the elements of the list | reduce([1, 4, 9], 0, (a, v) -> a + v) ⇒ 14 |
{emptylist=[]}
{if: count(emptylist) = 0}{error: "The list is empty"; block=yes}{endif}
{names=["John", "Sally", "Sue", "Greg"]}
{greetings=map(names, (name) -> "Hello " & name)}
{onlysnames=filter(names, (name) -> contains(name, "S"))}
Greetings: {=greetings} Names that contain an "S": {=onlysnames}
Ordered List Functions
The following functions only work on ordered lists.
Function | Description | Example |
---|---|---|
seq(start, end, step) | Creates an ordered list from start to end by step. If step is omitted, it defaults to 1 or -1. | seq(1, 3) ⇒ [1, 2, 3] |
split(str, del) | Creates an ordered list by splitting a string by a deliminator | split("a/b/c", "/") ⇒ ["a", "b", "c"] |
join(list, del) | Creates a string by joining the elements of a list | join([1, 3, 9], "-") ⇒ 1-3-9 |
sort(list, fn(a, b)) | Sorts the elements of the ordered list. fn(a, b) will be called for each pair of elements; if is negative, a will be placed before b; if positive, b will be placed before a; if 0, the elements are equivalent | sort([3, 9, 1], (a, b) -> a - b) ⇒ [1, 3, 9] |
slice(list, start, last) | Extract part of the list from start to last. If last is omitted, returns from start to the end of the list | slice([1, 4, 9, 16], 2, 3) ⇒ [4, 9] |
sum(list) | Sum the elements of a list | sum([1, 4, 10]) ⇒ 15 |
find(list, fn) | Returns the first element of a list that matches a condition | find([1, 4, 9], x -> x > 3) ⇒ 4 |
unique(list) | Removes duplicates | unique(["A", "A", "B"]) ⇒ ["A", "B"] |
Keyed List Functions
The following only work on Text Blaze's keyed lists.
Function | Description | Example |
---|---|---|
keys(list) | The keys in a keyed list as an ordered list | keys(["a": 123, "b": 345]) ⇒ ["a", "b"] |
Information Functions
The following functions all return a Boolean (yes/no) value. They're especially useful when used in combination with the {if} command.
Function | Description | Example |
---|---|---|
isnumber(x) | Whether a value is a number | isnumber("1.2") ⇒ yes |
isboolean(x) | Whether a value is a boolean | isboolean("no") ⇒ yes |
islist(x) | Whether a value is a list | islist([1,2,3]) ⇒ yes |
iserror(x) | Whether a value is an error | iserror(1 + "a") ⇒ yes |
Data Encoding Functions
These are very helpful functions to help with encoding. The urlencode()
and urldecode()
functions in particular are very useful when working with the {link} and {image} commands.
Function | Description | Example |
---|---|---|
urlencode(x) | Encodes special characters to allow including a string in a url | urlencode("a&b") ⇒ "a%26b" |
urldecode(x) | Decodes a urlencode d string | urlencode("a%26b") ⇒ "a&b" |
base64encode(x) | Base 64 encode a string | base64encode("hello") ⇒ "aGVsbG8=" |
base64decode(x) | Base 64 decode a string | base64decode("aGVsbG8=") ⇒ "hello" |
JSON Functions
There's a useful function built into Text Blaze that will help you work with JSON. This is very useful if you already have JSON and need this data available in your snippet.
Function | Description | Example |
---|---|---|
fromjson(str) | Converts a JSON string into a list | fromjson("{\"a\": [1,2,3]}") ⇒ ["a": [1, 2, 3]] |
Escaping Special Characters
Certain characters have special meaning in Text Blaze commands and strings. For instance, the ;
character is used to separate settings in commands. In formula strings, the "
character is used to signal the start and end of the string.
To use these special characters in their normal form you can "escape" them by placing a single backslash (\
) before them.
For example:
{="this is a \" character"}
will print:
this is a " character
The rules for escaping special characters are slightly different within commands and strings. The following table summarizes these rules:
In Commands | In Strings | |
---|---|---|
Common escapes: \n , \r , \t , \\ | Replaced with newline, carriage return, tab, and \ respectively | Replaced with newline, carriage return, tab, and \ respectively |
Special characters that need to be escaped | { , } , = , ; , and spaces at the start or end of a setting (and within the values of list settings: , ) | " |
Any other occurrences of \X | Backslashes are stripped. E.g. \a\b\c becomes abc | Backslashes remain. E.g. \a\b\c stays as \a\b\c |
Additional common escapes may be added to Text Blaze in the future, so you should be explicit with your backslashes and not accidentally rely on the behaviors in the third row of this table.
Special Delimiters
Text Blaze has two special delimiters you can use that join the items together using natural language concatenation: "BLAZE_AND"
and "BLAZE_OR"
. These can be particularly useful in the formatter
function for the {formmenu} command.
For example:
List Comprehensions
Text Blaze has powerful built-in functions for transforming lists: including filter()
, map()
, and reduce()
.
Sometimes though, it can be easier to use a powerful Text Blaze feature called list comprehensions if you need to transform a list. List comprehensions carry out an operation across each element of a list.
Imagine you wanted to square each element of an ordered list. The following example shows how to do that with both the map()
function and a list comprehension:
Map() version: {=map(n, x -> x^2)}
List comprehension version: {=[x^2 for x in n]}
Both work and are almost exactly the same length, but many people find the list comprehension version easier to read.
You can also include an optional if
block in your list comprehensions, items will only be included when it evaluates to yes
. Imagine we only wanted to include items who were larger than 20:
Filter() & Map() version: {=map(filter(n, x -> x > 20), x -> x^2)}
List comprehension version: {=[x^2 for x in n if x > 20]}
List Comprehensions with Keyed Lists
List comprehensions can also iterate across keyed lists and can create keyed lists. The following shows the examples of the different possible combinations:
Keyed List: {formtext: name=k; default=["a": 10, "b": 12, "c": 100]}
Ordered in and Ordered out: {=[x^2 for x in o]}
Ordered in and Keyed out: {=[index: x^2 for (x, index) in o]}
Keyed in and Ordered out: {=[value^2 for (key, value) in k]}
Keyed in and Keyed out: {=[key: value^2 for (key, value) in k]}
Multi-line formulas
Text Blaze supports multi-line formulas with code blocks.
Variable scopes
In general, all variables in Text Blaze are part of one global scope. There are a few exceptions to this. In these exceptions local scopes are created that have access to the global scope variables but may contain additional variables that are not in the global scope:
- The {repeat} command, creates a separate local scope for each iteration of the repeat]. This allows you to create form fields within repeat's that are independent of one another. You can use the {repeat} command's
locals
setting to access these local variables in your global scope. - User defined functions will create a local scope with any parameters passed to the function.
- Code blocks can create variables local to the code block using the
var
statement.
Regular Expressions
A regular expression pattern is composed of simple characters, such as "abc"
, or a combination of simple and special characters, such as "ab*c"
or "Chapter (\d+)\.\d*"
. The last example includes parentheses which can be used to extract specific parts of the regex using the extractregex()
function.
This section is adapted from this MDN Page by Mozilla Contributors and licensed under CC-BY-SA license.
Text Blaze provides you with a variety of regular expression built-in functions for you to leverage regular expressions with.
{if: testregex(number, "^\s*(\d\d\d)\s*\d\d\d-\d\d\d\d\s*$")}Area Code: {=extractregex(number, "((\d\d\d))")}{else}That is not a valid phone number.{endif}
Using simple patterns
Simple patterns are constructed of characters for which you want to find a direct match. For example, the pattern "abc"
matches character combinations in strings only when exactly the characters 'abc' occur together and in that order. Such a match would succeed in the strings "Hi, do you know your abc's?" and "The latest airplane designs evolved from slabcraft." In both cases, the match is with the substring 'abc'. There is no match in the string 'Grab crab' because while it contains the substring 'ab c', it does not contain the exact substring 'abc'.
Using special characters
When the search for a match requires something more than a direct match, such as finding one or more b's, or finding white space, the pattern includes special characters. For example, the pattern "ab*c"
matches any character combination in which a single 'a' is followed by zero or more 'b's (*
means 0 or more occurrences of the preceding item) and then immediately followed by 'c'. In the string "cbbabbbbcdebc," the pattern matches the substring 'abbbbc'.
The table at the end of this section provides a complete list and description of the special characters that can be used in regular expressions.
{formtext: cols=50; name=text; default=The phone number is 555-1842. I want to match it.}
Option 1: {=extractregex(text, "\d\d\d-\d\d\d\d")} Option 2: {=extractregex(text, "\d{3}-\d{4}")} Option 3: {=extractregex(text, "\d+-\d+")}
Special characters in regular expressions
The following table is a list of special characters that can be used in regular expressions:
Character | Meaning |
---|---|
\ | Matches according to the following rules: A backslash that precedes a non-special character indicates that the next character is special and is not to be interpreted literally. For example, a 'b' without a preceding '' generally matches lowercase 'b's wherever they occur. But a ' \b ' by itself doesn't match any character; it forms the special word boundary character.A backslash that precedes a special character indicates that the next character is not special and should be interpreted literally. For example, the pattern "a*" relies on the special character '\* ' to match 0 or more a's. By contrast, the pattern "a\*" removes the specialness of the '*' to enable matches with strings like 'a*'.To match a \ you need to escape it as \\ . If you are entering your regex as a string directly in your snippet, you will need to double escape it (\\\\ ) as a \\ is replaced by a single \ in Text Blaze quoted strings. |
^ | Matches the beginning of input. For example, "^A" does not match the 'A' in "an A", but does match the 'A' in "An E".The '^' has a different meaning when it appears as the first character in a character set pattern. See complemented character sets for details and an example. |
$ | Matches end of input. For example, "t$" does not match the 't' in "eater", but does match it in "eat". |
* | Matches the preceding expression 0 or more times. Equivalent to {0,} .For example, "bo*" matches 'boooo' in "A ghost booooed" and 'b' in "A bird warbled" but nothing in "A goat grunted". |
+ | Matches the preceding expression 1 or more times. Equivalent to {1,} .For example, "a+" matches the 'a' in "candy" and all the a's in "caaaaaaandy", but nothing in "cndy". |
? | Matches the preceding expression 0 or 1 time. Equivalent to {0,1} .For example, "e?le?" matches the 'el' in "angel" and the 'le' in "angle" and also the 'l' in "oslo".If used immediately after any of the quantifiers * , + , ? , or {} , makes the quantifier non-greedy (matching the fewest possible characters), as opposed to the default, which is greedy (matching as many characters as possible). For example, applying "\d+" to "123abc" matches "123". But applying "\d+?" to that same string matches only the "1". |
. | (The decimal point) matches any single character except the newline character. For example, ".n" matches 'an' and 'on' in "nay, an apple is on the tree", but not 'nay'. |
x|y | Matches 'x', or 'y' (if there is no match for 'x'). For example, "green|red" matches 'green' in "green apple" and 'red' in "red apple." The order of 'x' and 'y' matters. For example "a*|b" matches the empty string in "b", but "b|a*" matches "b" in the same string. |
{n} | Matches exactly n occurrences of the preceding expression. N must be a positive integer. For example, "a{2}" doesn't match the 'a' in "candy," but it does match all of the a's in "caandy," and the first two a's in "caaandy." |
{n,} | Matches at least n occurrences of the preceding expression. N must be a positive integer. For example, "a{2,}" will match "aa", "aaaa" and "aaaaa" but not "a" |
{n,m} | Where n and m are positive integers and n <= m. Matches at least n and at most m occurrences of the preceding expression. When m is omitted, it's treated as ∞. For example, "a{1,3}" matches nothing in "cndy", the 'a' in "candy," the first two a's in "caandy," and the first three a's in "caaaaaaandy". Notice that when matching "caaaaaaandy", the match is "aaa", even though the original string had more a's in it. |
[xyz] | Character set. This pattern type matches any one of the characters in the brackets, including escape sequences. Special characters like the dot(. ) and asterisk (* ) are not special inside a character set, so they don't need to be escaped. You can specify a range of characters by using a hyphen, as the following examples illustrate.The pattern [a-d] , which performs the same match as [abcd], matches the 'b' in "brisket" and the 'c' in "city". The patterns "[a-z.]+" and "[\w.]+" match the entire string "test.i.ng". |
[^xyz] | A negated or complemented character set. That is, it matches anything that is not enclosed in the brackets. You can specify a range of characters by using a hyphen. Everything that works in the normal character set also works here. For example, [^abc] is the same as [^a-c] . They initially match 'r' in "brisket" and 'h' in "chop." |
[\b] | Matches a backspace (U+0008). You need to use square brackets if you want to match a literal backspace character. (Not to be confused with \b .) |
\b | Matches a word boundary. A word boundary matches the position where a word character is not followed or preceded by another word-character. Note that a matched word boundary is not included in the match. In other words, the length of a matched word boundary is zero. (Not to be confused with [\b] .)Examples: "\bm" matches the 'm' in "moon" ;"oo\b" does not match the 'oo' in "moon", because 'oo' is followed by 'n' which is a word character;"oon\b" matches the 'oon' in "moon", because 'oon' is the end of the string, thus not followed by a word character;"\w\b\w" will never match anything, because a word character can never be followed by both a non-word and a word character.Note: The regular expression engine defines a specific set of characters to be "word" characters. Any character not in that set is considered a word break. This set of characters is fairly limited: it consists solely of the Roman alphabet in both upper- and lower-case, decimal digits, and the underscore character. Accented characters, such as "é" or "ü" are, unfortunately, treated as word breaks. |
\B | Matches a non-word boundary. This matches a position where the previous and next character are of the same type: Either both must be words, or both must be non-words. The beginning and end of a string are considered non-words. For example, "\B.." matches 'oo' in "noonday", and "y\B." matches 'ye' in "possibly yesterday." |
\d | Matches a digit character. Equivalent to [0-9] .For example, "\d" or "[0-9]" matches '2' in "B2 is the suite number." |
\D | Matches a non-digit character. Equivalent to [^0-9] .For example, "\D" or "[^0-9]" matches 'B' in "B2 is the suite number." |
\s | Matches a single white space character, including space, tab, form feed, line feed. For example, "\s\w*" matches ' bar' in "foo bar." |
\S | Matches a single character other than white space. For example, "\S*" matches 'foo' in "foo bar." |
\w | Matches any alphanumeric character including the underscore. For example, "\w" matches 'a' in "apple," '5' in "$5.28," and '3' in "3D." |
\W | Matches any non-word character. For example, "\W" matches '%' in "50%." |
More Regular Expression Examples
Let's build out a snippet to extract an email address.
Extracted Email: {=extractregex(text, "\w+@[.\w]+\b")}
Here's what's happening:
\w+@
is matching all word characters prior to the @
symbol.
[.\w]+\b
is matching as many periods and word characters as it can, up until a word boundary (meaning a punctuation mark followed by a space).
Here are some further clarifications of the special characters being used:
The period character (.
) has a special meaning in regex (see the list provided above). If you want RegEx to interpret the period character literally, you need to precede it with a backslash.
The square brackets mean "any combination of the included".
The \b
represents the word boundary.
Of course, this is just the tip of the iceberg with RegEx.
We're always improving the Text Blaze documentation to make things more clear for you.
Next Steps
- If you still have questions you can always post on our community. We're here to help!
- Go through our examples to see various commands and the formula language in use.
- Watch our YouTube videos for examples on using the Blaze Formula language and various commands.