Regex. Just the word is enough to make some developers break into a cold sweat. It’s one of those tools that can turn twenty lines of messy string-parsing logic into a single line of absolute gibberish. If you've been around the block, you know the drill: the first time you use regex, you have one problem. Now, you have two.
In Skink, we keep our std/regex implementation straightforward. No infinite look-aheads that crash your stack; just clean, predictable pattern matching.
Compiling a pattern
Before you can hunt for patterns, you have to compile them. It’s a bit of overhead, but it saves the engine from having to re-parse your intention every single time you search a line of text.
module main
import "std/regex"
fn main() -> int {
// Compiling the pattern... and keeping it simple.
re := regex.Compile("h?llo")
if re.Match("hello") {
print("matched hello")
}
return 0
}
In this pattern ? matches any single character. It's the "don't ask questions, just match it" wildcard.
Matching full strings
Match is a strict gatekeeper. It returns true only if the entire string conforms to the pattern from start to finish. If your pattern is cat and you feed it catalog, it’s going to say "no." It's not a suggestion; it's a rule.
re := regex.Compile("cat")
if re.Match("cat") { // true
print("exact match")
}
if re.Match("catalog") { // false
print("this won't run")
}
Finding a substring
If you're not looking for the whole string but just a needle in a haystack, use Find. It returns a match object that tells you exactly where the fun began.
re := regex.Compile("cat")
m := re.Find("concatenate cats")
if m.start >= 0 {
print("found '{m.text}' at {m.start}")
}
Wildcards: The secret sauce
* matches any sequence of characters (even an empty one—it's the optimistic wildcard).
? matches any single character.
re := regex.Compile("s*n")
if re.Match("shin") { // true: s...n
print("matched")
}
Replacing matches
Sometimes you just want to purge the old data and swap in the new. ReplaceAll does exactly what it says on the tin.
re := regex.Compile("cat")
result := re.ReplaceAll("one cat two cats", "dog")
print(result) // "one dog two dogs"
Exercises
- The Three-Letter Word: Compile a pattern that matches any 3-letter word starting with c. (Hint: use that ? wildcard.)
- The Searcher: Use Find to locate the first number in a string.
- The Micro-Grep: Write a small program that takes a file and prints every line that matches a specific pattern. It's the oldest trick in the Unix book, and it's still just as satisfying.
Next
When you're ready to start dealing with tabular data that’s as messy as the real world, we'll talk about Reading and writing CSV.