Regular Expressions
The Regex class provides powerful pattern-matching capabilities. It allows you to search, validate, and manipulate text using standard regular expressions. You must import this module using @import("std/regex").
Compiling a Regex
The Regex class cannot be instantiated using the standard constructor (it is marked with @no_constructor). Instead, you use the static factory method Regex.compile(pattern). This approach parses and compiles the pattern into a highly optimized format under the hood.
@import("std/regex")
// Remember to escape backslashes in Autolang strings!
// This pattern matches 1 or more digits.
val numberRegex = Regex.compile("\\d+")
println("Regex compiled successfully!")Validating Text
Use the isMatch() method to check if a string contains the pattern. This is incredibly useful for validating user inputs like emails, phone numbers, or passwords.
@import("std/regex")
// Simple email validation pattern
val emailRegex = Regex.compile("^[a-zA-Z0-9._]+@[a-zA-Z0-9]+\\.[a-zA-Z]+$")
val test1 = "user@autolang.com"
val test2 = "invalid-email@"
println("Is test1 valid? ${emailRegex.isMatch(test1)}") // true
println("Is test2 valid? ${emailRegex.isMatch(test2)}") // falseExtracting Data
If you need to extract all occurrences of a pattern from a large block of text, use the findAll() method. It returns an Array<String> containing all the matched results.
@import("std/regex")
val text = "Order #123 contains 5 apples and 12 bananas."
// Match all numbers
val numberRegex = Regex.compile("\\d+")
val numbers = numberRegex.findAll(text)
println("Found ${numbers.size()} numbers:")
func printNumber(num: String) {
println("- " + num)
}
numbers.forEach(printNumber)
// Output: 123, 5, 12Replacing Text
The replace() method allows you to substitute all matches of the pattern with a new string. This is perfect for masking sensitive data or cleaning up text formats.
@import("std/regex")
val document = "Contact us at 555-1234 or 555-9876."
// Match a basic phone number format (3 digits - 4 digits)
val phoneRegex = Regex.compile("\\d{3}-\\d{4}")
val masked = phoneRegex.replace(document, "[REDACTED]")
println(masked)
// Output: Contact us at [REDACTED] or [REDACTED].Reference
Static Factory Methods
Regex.compile(pattern: String): Regex- Compiles the given string pattern into a reusable Regex object.
Instance Methods
isMatch(text: String): Bool- Returnstrueif the pattern can be found anywhere within the provided text.findAll(text: String): Array<String>- Searches the text and returns an array of all substrings that match the pattern.replace(text: String, replacement: String): String- Replaces all occurrences of the pattern in the text with the specified replacement string and returns the new result.
