在 Perl 中,您将使用re::regexp_pattern
.
my $re = qr/foo/i;
my ($pat, $mods) = re::regexp_pattern($re);
say $pat; # foo
say $mods; # i
从 的源码可以看出,regexp_pattern
API 中没有获取该信息的函数,因此我建议您也从 XS 中调用该函数。
perlcall涵盖了从 C 调用 Perl 函数。我想出了以下未经测试的代码:
/* Calls re::regexp_pattern to extract the pattern
* and flags from a compiled regex.
*
* When re isn't a compiled regex, returns false,
* and *pat_ptr and *flags_ptr are set to NULL.
*
* The caller must free() *pat_ptr and *flags_ptr.
*/
static int regexp_pattern(char ** pat_ptr, char ** flags_ptr, SV * re) {
dSP;
int count;
ENTER;
SAVETMPS;
PUSHMARK(SP);
XPUSHs(re);
PUTBACK;
count = call_pv("re::regexp_pattern", G_ARRAY);
SPAGAIN;
if (count == 2) {
/* Pop last one first. */
SV * flags_sv = POPs;
SV * pat_sv = POPs;
/* XXX Assumes no NUL in pattern */
char * pat = SvPVutf8_nolen(pat_sv);
char * flags = SvPVutf8_nolen(flags_sv);
*pat_ptr = strdup(pat);
*flags_ptr = strdup(flags);
} else {
*pat_ptr = NULL;
*flags_ptr = NULL;
}
PUTBACK;
FREETMPS;
LEAVE;
return *pat_ptr != NULL;
}
用法:
SV * re = ...;
char * pat;
char * flags;
regexp_pattern(&pat, &flags, re);