Regex: Replacing depending on the match

When doing a substitution, is it possible, to have a group of optional items, and on the replace, replace those optional values with a differnt value?

Example:

s/(Monday|Tuesday|Wednesday)/

so how could I go about telling it, if you found Monday, replace with Mon. if you found Tuesday, replace with Tue.

My statement is more complicated that this, but one of the groups I would like to have optional replacements for each item and I'm not sure if it is possible.

Comments

  • With that example, it would be fairly simple - I think
    s/(Monday|Tuesday|Wednesday)/substr $1,0,3/e
    would work. For more complicated things though, it would naturally be harder. Multiple matches would be the obvious solution, or you could do an if-then-else on $1 (or other $numbers if you have more sets of brackets).
  • : With that example, it would be fairly simple - I think
    : s/(Monday|Tuesday|Wednesday)/substr $1,0,3/e
    : would work. For more complicated things though, it would naturally be harder. Multiple matches would be the obvious solution, or you could do an if-then-else on $1 (or other $numbers if you have more sets of brackets).
    :
    Putting if...then...elsif...else stuff in would be possible, but ugly. ... ? ... : ... may possibly be less messy, but still not much. If you don't want to do multiple matches, a neater way might be to define subroutines to handle each case.

    sub Monday {
    return 'Mon';
    }
    sub Tuesday {
    return 'Tue';
    }
    sub Wednesday {
    return 'Wed';
    }

    Then do a runtime sub lookup and call...

    s/(Monday|Tuesday|Wednesday)/&{$1}/e

    Or something of the like. Take the usual precautions about what you feed into there as it will get evaluated.

    Jonathan

    ###
    for(74,117,115,116){$::a.=chr};(($_.='qwertyui')&&
    (tr/yuiqwert/her anot/))for($::b);for($::c){$_.=$^X;
    /(p.{2}l)/;$_=$1}$::b=~/(..)$/;print("$::a$::b $::c hack$1.");

Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories