Zig Requires Chilkat v11.1.0+
Zig
Regular Expression with Named Capture Groups
See more Regular Expressions Examples
Demonstrates regular expressions with named capture groups.See the sample code below.
Note: Chilkat uses PCRE2. See PCRE2 Regular Expressions
Also see: PCRE2 Performance
In PCRE2, named capture groups allow you to assign a name to a capturing group, making it easier to reference by name instead of number.
Syntax
(?<name>pattern)
or
(?'name'pattern)
Example
(?<first>\w+)\s+(?<last>\w+)
Applied to:
"John Smith"
Produces:
first:Johnlast:Smith
Chilkat Zig Downloads
const std = @import("std");
const chilkat = @import("chilkat");
pub fn main(init: std.process.Init) !void {
const alloc = init.arena.allocator();
const subject = "John Smith";
const pattern = "(?<first>\\w+)\\s+(?<last>\\w+)";
const sb = try chilkat.StringBuilder.init();
defer sb.deinit();
sb.append(subject) catch {};
const json = try chilkat.JsonObject.init();
defer json.deinit();
json.setEmitCompact(false);
const timeout_ms = 2000;
const num_matches = sb.regexMatch(pattern, json, timeout_ms);
if (num_matches < 0) {
// Probably an error in the regular expression.
// Suggestion: Use AI to help create and/or diagnose regular expressions.
std.debug.print("{s}\n", .{try sb.getLastErrorText(alloc)});
return;
}
// Examine the matches:
std.debug.print("{s}\n", .{try json.emit(alloc)});
// Here is the JSON showing the matches.
// Important: Capture group 0 always contains the entire match — that is, the portion of the input string that matches the full regular expression.
// {
// "named": {
// "first": 1,
// "last": 2
// },
// "match": [
// {
// "group": [
// {
// "cap": "John Smith",
// "idx": 0,
// "len": 10
// },
// {
// "cap": "John",
// "idx": 0,
// "len": 4
// },
// {
// "cap": "Smith",
// "idx": 5,
// "len": 5
// }
// ]
// }
// ]
// }
// The capture group index is obtained by looking up the name in the JSON result.
// For example:
json.setI(json.intOf("named.first"));
std.debug.print("first: {s}\n", .{try json.stringOf(alloc, "match[0].group[i].cap")});
json.setI(json.intOf("named.last"));
std.debug.print("last: {s}\n", .{try json.stringOf(alloc, "match[0].group[i].cap")});
// Output is:
// first: John
// last: Smith
}