Usage
The 7 examples below are taken from zig-regex's README.
.dependencies = .{
.regex = .{
.url = "https://github.com/zig-utils/zig-regex/archive/main.tar.gz",
.hash = "...", // zig will provide this
},
},
const regex = b.dependency("regex", .{
.target = target,
.optimize = optimize,
});
exe.root_module.addImport("regex", regex.module("regex"));
const std = @import("std");
const Regex = @import("regex").Regex;
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
const allocator = gpa.allocator();
var regex = try Regex.compile(allocator, "\\d{3}-\\d{4}");
defer regex.deinit();
if (try regex.find("Call me at 555-1234")) |match| {
var mut_match = match;
defer mut_match.deinit(allocator);
std.debug.print("Found: {s}\n", .{match.slice}); // "555-1234"
}
}
var regex = try Regex.compile(allocator, "\\d+");
defer regex.deinit();
const matches = try regex.findAll(allocator, "a1b23c456");
defer {
for (matches) |*m| {
var mut_m = m;
mut_m.deinit(allocator);
}
allocator.free(matches);
}
// matches: "1", "23", "456"
var regex = try Regex.compile(allocator, "(\\w+)@(\\w+)");
defer regex.deinit();
const result = try regex.replace(allocator, "email: user@host ok", "[$0]");
defer allocator.free(result);
// result: "email: [user@host] ok"
var regex = try Regex.compile(allocator, "(\\d{4})-(\\d{2})-(\\d{2})");
defer regex.deinit();
if (try regex.find("Date: 2024-03-15")) |match| {
var mut_match = match;
defer mut_match.deinit(allocator);
// match.captures[0] = "2024"
// match.captures[1] = "03"
// match.captures[2] = "15"
}
var regex = try Regex.compileWithFlags(allocator, "^hello", .{
.case_insensitive = true,
.multiline = true,
});
defer regex.deinit();