ronsavage/Regexp-Assemble

When tracking, return a data item instead of the matched regex?

Opened this issue · 0 comments

cxw42 commented

My use case is normalizing input. Is there a way to associate my normalized input value with a regex so I can get that input value instead of the matched regex itself?

The following code works but is rather verbose:

state %STRATEGIES = (   # regex => strategy
    '(<undef>|combine)' => 'combine',
    '(first|keep)' => 'keep',
    '(last|replace)' => 'replace',
);
state $STRATEGY_MAP = Regexp::Assemble->new->flags('i')->track(1)
    ->anchor_string_begin->anchor_string_end
    ->add(keys %STRATEGIES);

my $merge_strategy_idx = $STRATEGY_MAP->match($strategy // '<undef>');
     # Returns '(<undef>|combine)', '(first|keep)', ...
die unless defined $merge_strategy_idx;
my $merge_strategy = $STRATEGIES{$merge_strategy_idx};

I would instead like to be able to do something like:

state $STRATEGY_MAP = Regexp::Assemble->new->flags('i')->track(1)
    ->anchor_string_begin->anchor_string_end
    ->add({re => '(<undef>|combine)', tag => 'combine'},
        {re=>'(first|keep)', tag => 'keep'},
        {re=>'(last|replace)', tag => 'replace'});

my $merge_strategy = $STRATEGY_MAP->match_tag($strategy // '<undef>');
    # Returns 'combine', 'keep', 'replace', or undef
die unless defined $merge_strategy_idx;

I looked in the documentation but did not see a way to do this in the code as it stands. Would you please let me know if there is a way, or whether you would be open to a PR to add it? Thanks!