Search code examples
regexperl

Regex: ignore character on several different positions


Given this string: W1_R23_4_56_78

Searched is: R2345678 (in one match) all from the 4th position without any _

^.{3}\K.[^_]* 

gives R23

Is it possible to get one match or is it done by substitution or ...

Thanks in advance to guiding the right direction


Solution

  • One way to capture all after position 3, without underscores, and join into a wanted string

    my $str = 'W1_R23_4_56_78';
    
    pos $str = 3;
    
    my $res = join '', $str =~ /[^_]+/g;
    

    That pos allows to change offset for the next search, see docs. Note that this affects some future operations (do see the docs).

    The following matching is in the list context, imposed by join, so the matches are returned. (In patterns that match more than what we want we'd need to have the capturing parenthesis for the wanted parts so that only those are returned.)