String.match (regex)

Welcome to the HaasScript String Matching course! In this course, we will be exploring the string.match function in HaasScript, which is used to search for patterns in strings. To use this function effectively, it is important to understand the basics of regular expressions (regex), which are patterns used to match character combinations in strings. Here is a brief overview of regex:

Regular Expressions

Regular expressions are a powerful tool for manipulating and searching text. They are used to match patterns in strings and can be used in many programming languages, including HaasScript. Here are some commonly used regex parameters:

ParameterDescription
.Matches any single character except for newline
*Matches zero or more occurrences of the previous character
+Matches one or more occurrences of the previous character
?Matches zero or one occurrence of the previous character
[]Matches a character from a set of characters
()Groups characters together

Now that we have an understanding of regex, let’s dive into the string.match function in HaasScript.

The string.match Function

The string.match function in HaasScript is used to search for a pattern in a string and return the matching text. It takes two arguments: the string to search and the pattern to match. Here’s an example:

local str = "The quick brown fox jumps over the lazy dog."
local pattern = "%a+"

local match = string.match(str, pattern)
Log(match) -- prints "The"

In this example, we are searching for the first word in the string ("The") using the pattern "%a+". Let’s break down this pattern:

  • %a matches any alphabetical character
  • + matches one or more occurrences of the previous character or pattern

So, "%a+" matches any sequence of alphabetical characters. In this case, it matches "The", which is the first word in the string.

Here’s another example:

local str = "The quick brown fox jumps over the lazy dog."
local pattern = "fox"

local match = string.match(str, pattern)
Log(match) -- prints "fox"

In this example, we are searching for the word "fox" in the string. The pattern simply matches the characters "fox", so that is what is returned.

As you can see, the string.match function can be a powerful tool for searching and manipulating strings in HaasScript. By understanding the basics of regex, you can create patterns that match specific patterns in your strings and use them to extract or replace text as needed.

Back to: HaasScript Fundamentals > Strings