Commit 8d3205ea
8d3205ea401eMerged
Yukihiro "Matz" Matsumoto <[email protected]> · 5 months ago · 1 file · ~1 modified
Description
String#[] with a regex returns the matched substring
s[/re/] (and the slice alias) now returns the matched substring, or nil when the pattern does not match, using the engine's last-match buffer. Works with inline and constant-bound patterns.
Co-Authored-By: Claude Opus 4.8 [email protected]
Details
- Commit
- 8d3205ea401e
- Parent
- 8b8859c42730
src/codegen.cmodifiedView file
@@ -3808,6 +3808,10 @@
38083808
else if (!strcmp(name, "crypt") && argc == 1) { buf_printf(b, "sp_str_crypt(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ")"); }38093809
else if (!strcmp(name, "scrub") && argc == 0) buf_printf(b, "sp_str_scrub(%s, 0)", r);38103810
else if (!strcmp(name, "scrub") && argc == 1) { buf_printf(b, "sp_str_scrub(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ")"); }3811+
else if ((!strcmp(name, "[]") || !strcmp(name, "slice")) && argc == 1 && re_lit_index(c, argv[0]) >= 0) {3812+
/* s[/re/] -> the matched substring, or nil (NULL) on no match */3813+
buf_printf(b, "(sp_re_match(sp_re_pat_%d, %s) >= 0 ? sp_re_match_str : NULL)", re_lit_index(c, argv[0]), r);3814+
}38113815
else if ((!strcmp(name, "[]") || !strcmp(name, "slice")) && argc == 1 && nt_type(c->nt, argv[0]) &&38123816
!strcmp(nt_type(c->nt, argv[0]), "RangeNode")) {38133817
/* s[a..b] / s[a...b]; beginless/endless ranges use 0 / length */